Search code examples
javascriptionic-frameworkgoogle-maps-api-3google-polyline

Draw Polyline between markers Ionic Google Maps JavaScript


Hi guys this is my first post in this site, im working in a App in Ionic that shows your position with a marker when you push a button, you can push it again to update your position and add a Marker on that position, i want to draw a Polyline between this markers but i havent succeed yet. i know there are some ways to draw polylines my idea is to extract the lat, long coordinates of the marker, save them in a array and then set that as a "path" to draw the Polyline but im having problems with the creation of the array like in the comment below. here is my code:

        import { Component, ViewChild, ElementRef } from '@angular/core';
        import { NavController} from 'ionic-angular';
        import { Geolocation } from '@ionic-native/geolocation';

    declare var google;
    @Component({
      selector: 'home-page',
      templateUrl: 'home.html'
    })

export class HomePage {

  @ViewChild('map') mapElement: ElementRef;
  map: any;
  me: any;
  markers=[];
  lat=[];
  long=[];
  constructor(public navCtrl: NavController, public geolocation: Geolocation) {
  }

  ionViewDidLoad(){
    this.loadMap();
  }

  loadMap() {

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

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

      let mapOptions = {
        center: mylatLng,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
    },
    (err) => {
      console.log(err);
    });
  }


    addMarker(){
     let marker = new google.maps.Marker({
        map: this.map,
      animation: google.maps.Animation.DROP, 
      });

      let content = '<p>Posición: ' + marker.setPosition() + '</p>'

      if (navigator.geolocation) navigator.geolocation.getCurrentPosition(function(pos) {
        var me = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
        marker.setPosition(me);


    }, 
    function(error) {
        // ...
    });    
        this.markers.push(marker);

        this.addInfoWindow(marker, content);
}
  addInfoWindow(marker, content){

    let infoWindow = new google.maps.InfoWindow({
      content: content
    });
    if (navigator.geolocation) navigator.geolocation.getCurrentPosition(function(pos) {
      var me = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
      infoWindow.setContent('<p>Posición: ' + me + '</p>')
      }, 
      function(error) {
      // ...
     });     

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

  setMapAll(map) {
    for (var i = 0; i < this.markers.length; i++) {
      this.markers[i].setMap(map);
    }
  }
  clearMarkers() {
    this.setMapAll(null);
  }


  deleteMarkers() {
    this.clearMarkers();
    this.markers = [];
  }
// Im having problems here

  addPolyLine() {
    var poly = new Array();
    for (var j=0; j<this.lat.length;j++){
    var pos= new google.maps.LatLng(this.lat[j],this.long[j])
    poly.push(pos);
  }

      var flightPath = new google.maps.Polyline({

        path: poly,
        geodesic: true,

        strokeColor: '#FF0000',

        strokeOpacity: 1.0,

        strokeWeight: 2

      });

      flightPath.setMap(this.map);

  }

}

And the HTML page:

<ion-header>
  <ion-navbar>
    <ion-title>
      MapaPrueba
    </ion-title>
    <ion-buttons end>
      <button ion-button (click)="addMarker()"><ion-icon name="add"></ion-icon>Agregar Pos</button>
    </ion-buttons>  
  </ion-navbar>
</ion-header>

<ion-content>
  <div #map id="map"></div>  

  <ion-fab left bottom>
    <button ion-fab color="light" (click)="clearMarkers()">
      <ion-icon name="eye-off"></ion-icon>
    </button>
  </ion-fab>
</ion-content>

Solution

  • There is a full example of that in the official documentation and here below as well.

    In short you have to:

    1. Create a Polyline and set it on the map (one time)
    2. Get the Polyline path with the Polyline getPath() method
    3. Push your new coordinates to the path

    var map;
    var polyLine;
    var polyOptions;
    
    function initialize() {
        
        var mapOptions = {
            zoom: 5,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: new google.maps.LatLng(0,0)
        };
    
        map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    
        polyOptions = {
            strokeColor: '#0026b3',
            strokeOpacity: 1.0,
            strokeWeight: 1,
            geodesic: true,
        }
    
        polyLine = new google.maps.Polyline(polyOptions);
        polyLine.setMap(map);
        
        google.maps.event.addListener(map, 'click', function(event) {
    
            addPoint(event);
        });
    }
    
    function addPoint(event) {
     
        var path = polyLine.getPath();
        path.push(event.latLng);
    
        var marker = new google.maps.Marker({
            position: event.latLng,
            map: map,
        });
        
        map.setCenter(event.latLng);
    }
    
    initialize();
    #map-canvas {
      height: 200px;
    }
    <div id="map-canvas"></div>
    <script src="https://maps.googleapis.com/maps/api/js"></script>