nativescript-google-maps-sdk:在运行时设置纬度和经度时,地图中心不正确



nativescript-google-maps-sdk

我在 OnInit 运行时设置纬度和经度值,但地图未正确居中(它以 0º 纬度和 0º 经度为中心)。 我尝试使用mapView.updateCamera(),但它不会刷新位置。 我还设置了一个具有相同纬度和纬度值的标记,并且它在地图上正确显示,因此我的变量具有正确的值(我也已使用 console.log 进行了检查)。 但是,如果在类中的声明处设置了纬度和经度,则地图居中良好。

这是map.component.ts:

import { Component, ElementRef, ViewChild, OnInit } from '@angular/core';
import { registerElement } from 'nativescript-angular/element-registry';
import { MapView, Marker, Position, latitudeProperty } from 'nativescript-google-maps-sdk';
// Important - must register MapView plugin in order to use in Angular templates
registerElement("MapView", () => require("nativescript-google-maps-sdk").MapView);
import { ActivatedRoute } from "@angular/router";

@Component({
moduleId: module.id,
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
//latitude =  38.735231; //Map is centered correctly if uncommented
//longitude = -9.146986; //Map is centered correctly if uncommented
latitude: number;   //Initialized in ngOnInit()!
longitude: number;  //Initialized in ngOnInit()!
zoom = 17;
bearing = 0;
tilt = 0;
padding = [40, 40, 40, 40];
mapView: MapView;
lastCamera: String;
constructor(private route: ActivatedRoute, ) {
}
ngOnInit() {
this.latitude = this.route.snapshot.params["lat"];
this.longitude = this.route.snapshot.params["lon"];
console.log("1- Lat: " + this.latitude + ", Lon: " + this.longitude); //OK!
}
//Map events
onMapReady(event) {
console.log('Map Ready');
this.mapView = event.object;
console.log("2- Lat: " + this.latitude + ", Lon: " + this.longitude); //OK!
this.mapView.updateCamera(); //NOT working!!!
console.log("Setting a marker...");
var marker = new Marker();
marker.position = Position.positionFromLatLng(this.latitude, this.longitude);
marker.title = "JLD Saldanha";
marker.snippet = "Av. Duque D'Avila, n°46C 1050-053 Lisboa";
marker.userData = { index: 1 };
this.mapView.addMarker(marker);
marker.showInfoWindow();

}
onCoordinateTapped(args) {
console.log("Coordinate Tapped, Lat: " + args.position.latitude + ", Lon: " + args.position.longitude, args);
}
onMarkerEvent(args) {
console.log("Marker Event: '" + args.eventName
+ "' triggered on: " + args.marker.title
+ ", Lat: " + args.marker.position.latitude + ", Lon: " + args.marker.position.longitude, args);
}
onCameraChanged(args) {
console.log("Camera changed: " + JSON.stringify(args.camera), JSON.stringify(args.camera) === this.lastCamera);
this.lastCamera = JSON.stringify(args.camera);
}
}

问题已解决:

问题是角度中的路由参数是字符串,组件变量纬度和经度是数字,因此无法在 OnInit 中正确分配值。

通过添加 + 前缀将字符串转换为数字解决了问题:

ngOnInit() 
{ 
this.latitude = +this.route.snapshot.params["lat"]; 
this.longitude = +this.route.snapshot.params["lon"]; 
}

最新更新