Using geolocation and infowindow: Ionic Google Maps Markers

1

In an app using Google Maps JavaScript API, I need to obtain the bookmarks from a JSON file, importing the relevant plugins I found a tutorial that works, I need to do geolocation, but no allows to use loadMap but displayGoogleMap , I'll leave the code below.

export class HomePage {

  @ViewChild('mapContainer') mapContainer: ElementRef;
  map: any;

  constructor(public navCtrl: NavController, public http: Http) {
  }

  ionViewWillEnter() {
    this.displayGoogleMap();
    this.getMarkers();
  }

  displayGoogleMap() {
    let latLng = new google.maps.LatLng(57.8127004, 14.2106225);

    let mapOptions = {
      center: latLng,
      disableDefaultUI: true,
      zoom: 11,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    this.map = new google.maps.Map(this.mapContainer.nativeElement, mapOptions);
  }

  getMarkers() {
    this.http.get('assets/data/markers.json')
    .map((res) => res.json())
    .subscribe(data => {
      this.addMarkersToMap(data);
    });
  }

  addMarkersToMap(markers) {
    for(let marker of markers) {
      var position = new google.maps.LatLng(marker.latitude, marker.longitude);
      var miMarker = new google.maps.Marker({position: position, title: marker.title});
      miMarker.setMap(this.map);
    }
  }
}
    
asked by Vladimir Yanken Cifuentes 25.05.2017 в 00:42
source

1 answer

0

For that you must install the Cordova GeoLocation plugin:

ionic plugin add cordova-plugin-geolocation

And also the native one

npm install --save @ionic-native/geolocation

Import into your controller

import { Geolocation } from '@ionic-native/geolocation';

And then when you draw the map:

this.geolocation.getCurrentPosition().then((position) => {

  let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

  let mapOptions = {
    center: latLng,
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

}, (err) => {
  console.log(err);
});

where this.geolocation.getCurrentPosition().then((position) gets the current position of the user

Within your code you must change

getMarkers() {
    this.http.get('assets/data/markers.json')
    .map((res) => res.json())
    .subscribe(data => {
         this.addMarker(data);
    });
}

To add bookmarks:

addInfoWindow(marker, content) {

    let infoWindow = new google.maps.InfoWindow({
        content: content
    });

    google.maps.event.addListener(marker, 'click', () => {
        infoWindow.open(this.map, marker);
    });

}

addMarker(markers) {
    for (let marker of markers) {
        let position = {marker.lat, marker.lng};
        let marker_custom = new google.maps.Marker({
            map: this.map,
            position: position
        });
        let content = marker.title;          

        this.addInfoWindow(marker_custom, content);
    }
}
    
answered by 25.05.2017 в 02:46