如何在ionic2中将标记移动到地图上?

时间:2017-07-23 16:49:35

标签: google-maps-api-3 ionic2 google-geolocation

在这段代码中,我尝试移动marker,因为我改变了位置,但似乎出现了问题。标记没有替换。

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: 17,
        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[0].lat= position.coords.latitude;
    this.marker[0].lng= position.coords.longitude;
    this.speed =( +position.coords.speed*3.6 ) + 'Km/h';
  });

});

}
addMarker(){

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

 this.marker.push(marker);
 console.log(this.marker);
}
}

}

1 个答案:

答案 0 :(得分:2)

使用setPosition移动标记。试试这个

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';
  });