RSA
RSA

Reputation: 1449

how to keep replacing marker always in visible area in ionic 2?

In fallowing code when marker is replacing in long distances it goes to out of screen, therefore user should manually drag map to keep marker in center/visible area of screen. is there any possible way to keep marker over map in visible area?

declare var google;
@Component({
  selector: 'page-page1',
  templateUrl: 'page1.html',
  providers: [Geolocation]
})
export class Page1 {
  @ViewChild('map') mapElement: ElementRef;
  map: any;
  public marker ;
  public lat;
  public lng;
  public speed = '0';
  public watch: any;
  constructor(public navCtrl: NavController, public Geolocation: Geolocation, public zone: NgZone,
  ) {}
ionViewDidLoad(){
  this.loadMap();
    this.startTracking();

  }

  loadMap(){

      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);
 this.addMarker();
    }, (err) => {
      console.log(err);
    });

  }
  startTracking() {
  let config = {
    desiredAccuracy: 0,
    stationaryRadius: 20,
    distanceFilter: 10, 
    debug: true,
    interval: 2000 
  };


let options = {
  frequency: 3000, 
  enableHighAccuracy: true
};

this.watch = this.Geolocation.watchPosition(options).filter((p: any) => p.code === undefined).subscribe((position: Geoposition) => {
  this.zone.run(() => {
    this.lat = position.coords.latitude;
    this.lng = position.coords.longitude;
    this.marker.setPosition({lat: this.lat, lng: this.lng});
    this.speed =( +position.coords.speed*3.6 ) + 'Km/h';
  });

});

}
stopTracking() {
  console.log('stopTracking');
  this.watch.unsubscribe();

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

}

Upvotes: 2

Views: 251

Answers (1)

Swapnil Patwa
Swapnil Patwa

Reputation: 4089

Use setCenter to center map when marker move.

this.zone.run(() => {
    this.lat = position.coords.latitude;
    this.lng = position.coords.longitude;
    this.marker.setPosition({lat: this.lat, lng: this.lng});

    this.map.setCenter({lat: this.lat, lng: this.lng});

    this.speed =( +position.coords.speed*3.6 ) + 'Km/h';
  });

Upvotes: 2

Related Questions