简体   繁体   中英

ionic 2 dynamic markers in Google Maps with profile picture

I am building an ionic2 application with tracking data stored in the database, i am able to get geolocation data and initialise a map, but i have an array of markers with profileimageurl and lat lng values, i am trying to bring the list of markers on the map with the profileimageurl as icon, but it did not work

Google map Init

initMap(): Promise<void> {
 let promise: Promise<void> = new Promise<void>((resolve, reject) => {
  Geolocation.getCurrentPosition().then((position) => {
    let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    let GooleMap = new google.maps.Map(document.getElementById('map'), {
      center: latLng,
      zoom: 18
    });
    let marker = new google.maps.Marker({
      position: latLng,
      map: GooleMap,
      title: 'My Location',
    });
  });
 });
 return promise;
}

Markers array

  markers: marker[] = [
  {
      lat: 51.673858,
      lng: 7.815982,
      label: 'A',
      profileImage: "http://www.gravatar.com/avatar/d735414fa8687e8874783702f6c96fa6?s=90&d=identicon&r=PG"
  },
  {
      lat: 51.373858,
      lng: 7.215982,
      label: 'B',
      profileImage: "http://placekitten.com/90/90"
  }
]

I am expecting a result something like this 在此处输入图片说明

I have been struggling with this for a while, i would much appreciate an answer, Thank you

I would override google.maps.OverlayView to implement it.

class CustomMarker extends google.maps.OverlayView {
  marker: any;
  clickListener: google.maps.MapsEventListener;

  constructor(private latlng, map, private args) {
    super();
    this.setMap(map);
  }

  draw() {
    const panes = this.getPanes();
    let marker = this.marker;

    if (!marker) {
      marker = this.marker = document.createElement('div');
      marker.className = 'marker';

      let img = document.createElement('img');
      img.src = this.args.img;
      marker.appendChild(img);

      let point = this.getProjection().fromLatLngToDivPixel(this.latlng);
      if (point) {
        marker.style.left = (point.x - 50) + 'px';
        marker.style.top = (point.y - 50) + 'px';
      }

      this.clickListener = google.maps.event.addDomListener(marker, "click", (event) => {
        alert('You clicked on a custom marker!');
        google.maps.event.trigger(this, "click");
      });

      panes.overlayImage.appendChild(marker);
    }
  }

  remove() {
    if (this.marker) {
      this.marker.parentNode.removeChild(this.marker);
      this.clickListener.remove();
      this.marker = null;
    }
  }

  getPosition() {
    return this.latlng;
  }
}

Plunker Example

PS I guess you have installed @types/google-maps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM