-2

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>
Doate
  • 5
  • 1
  • 6
  • I've tried using the native SDK on Ionic but it doesn't work the way i want, that's why im using the JavaScript version of GoogleMaps. English is not my native language and i apologize in advance. – Doate Feb 27 '18 at 22:46
  • 1
    *but im having problems with that* - what problems? – MrUpsidown Feb 28 '18 at 09:54
  • I've tried making the array that i mentioned above but the polyline doesnt appear, im a begginner in JavaScript and Ionic, with my research i've tried this: `var poly = new Array(); for (var j=0; j – Doate Feb 28 '18 at 16:49
  • what about accepting the answer that was provided to you, as you confirmed it worked and helped? – MrUpsidown Mar 20 '18 at 14:37

1 Answers1

0

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>
MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
  • I've tried and it works, thank you very much for the quick response, is there a way to add a Polyline pressing a button instead of clicking in the map?, im not totally sure but i think it has a relation with "AddDomListener", Do you know about this? – Doate Mar 02 '18 at 03:13
  • Yes, `addListener` is for registering events with the Maps elements (map, marker, polyline, etc.) and `addDomListener` is for registering DOM events (anything external to the map). There is [an example here](https://developers.google.com/maps/documentation/javascript/examples/event-domListener). So in your case you could register a DOM listener for your button click, and from within the listener, geolocalize the user, add a marker, a new point for the polyline, etc. – MrUpsidown Mar 02 '18 at 07:55