1
votes

I have added google maps API of JavaScript in angular 2. Added custom markers on the map according to positions fetched from API. I have displayed list of positions on UI. After click on position I want to replace that position's corresponding marker icon and reset all other icons. Following code is not working as expected.

I have added this function to place markers on map:

placeMarkers(markers: any, infoWindowContent: any) {
    // Display multiple markers on a map
    let infoWindow = new google.maps.InfoWindow();
    let bounds = new google.maps.LatLngBounds();
    let marker;

    // Loop through our array of markers & place each one on the map
    for(let i = 0; i < markers.length; i++ ) {
      let position = new google.maps.LatLng(<number>markers[i].lat, <number>markers[i].lang);
      bounds.extend(position);
      marker = new google.maps.Marker(<google.maps.MarkerOptions>{
        position,
        map: this.map,
        title: markers[i].name,
        icon: this.iconUrl,
      });

      // Allow each marker to have an info window
      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infoWindow.setContent(infoWindowContent[i]);
          infoWindow.open(this.map, marker);
        }
      })(marker, i));

      // Automatically center the map fitting all markers on the screen
      this.map.fitBounds(bounds);
    }
  }   

And this code to replace marker of selected position:

selectSite(site: any, index: any) {
    this.placeMarkers(this.finalMarkers, this.finalInfoWindowContent);

    let selection = this.finalMarkers.find(function(item) {
          return  item.name == site.Name
    });

    let infowindow = new google.maps.InfoWindow();
    let position = new google.maps.LatLng(<number>selection.lat, <number>selection.lang);

    let redMarker = new google.maps.Marker(<google.maps.MarkerOptions>{
      position: position,
      map: this.map,
      title: selection.name,
      icon: {url: require('../../../assets/img/red-marker.png'), scaledSize: {height: 30, width: 20}}
    });
      redMarker.addListener('click', function() {
      infowindow.setContent(selection.name);
      infowindow.open(this.map, redMarker);
    });
  }

Above code is working fine initially, but got stuck after multiple location changes. Any help is very much appreciated!

2

2 Answers

0
votes
**You can Set Following marker**

var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
        var icons = {
          parking: {
            icon: iconBase + 'parking_lot_maps.png'
          },
          library: {
            icon: iconBase + 'library_maps.png'
          },
          info: {
            icon: iconBase + 'info-i_maps.png'
          }
        };
0
votes

This is how I did it.

I simply did it outside google maps and it works great.

https://youtu.be/2cA3pQQoEr8