Quantcast
Channel: Ionic Framework - Ionic Forum
Viewing all articles
Browse latest Browse all 49253

Update google marker with watchposition

$
0
0

@TaimoorMughal wrote:

I am creating a map to track user position, i am using @geolocation plugin and showing map using:

    <script src="https://maps.googleapis.com/maps/api/js?key=API_KEYscript>

Currently marker is being displayed and on watchposition marker is placing multiple times and isn’t removing last placed marker.

import { Component, ViewChild, ElementRef } from '@angular/core';
import { Geolocation, GeolocationOptions, Geoposition, PositionError } from '@ionic-native/geolocation';
declare var google;

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {

  geolocation = Geolocation;
  options: GeolocationOptions;
  currentPos: Geoposition;
  @ViewChild('map', { static: false }) mapElement: ElementRef;
  map: any;

  constructor() { }

  ionViewDidEnter() {
    this.getUserPosition();
  }

  getUserPosition() {
    this.options = {
      enableHighAccuracy: false
    };
    //get location
    this.geolocation.getCurrentPosition(this.options).then((pos: Geoposition) => {
      this.currentPos = pos;
      console.log(pos);

      //add map
      let latLng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
      let mapOptions = {
        center: latLng,
        zoom: 18,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
      this.addMarker(latLng);
    }, (err: PositionError) => {
      console.log("error : " + err.message);
    })

    let subscription = this.geolocation.watchPosition().subscribe(position =>{
      let userPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
          this.addMarker(userPosition);
    })
  }

  addMarker(position) {
    let marker = new google.maps.Marker({
      map: this.map,
      animation: google.maps.Animation.DROP,
      position: position
    });
    let content = "<p>This is your current position !</p>";
    let infoWindow = new google.maps.InfoWindow({
      content: content
    });
    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.open(this.map, marker);
    });
  }

}

I want to remove last marker before placing another one.
Thank you.

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 49253

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>