jed*_*ard 8 google-maps typescript angular2-google-maps angular
我正在一个页面中实现一个谷歌地图,其中一个地方ID传递给我,然后我需要获得这样的地方ID并加载该标记的地图.我正在浏览文档,但不清楚如何从<agm-map>
标记中定位地图对象,以便我可以设置地点ID.以下是代码的一部分:
public latitude: number;
public longitude: number;
public zoom: number;
public placeid: string;
constructor(
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone
) {}
ngOnInit() {
//set google maps defaults
this.zoom = 4;
this.latitude = 39.8282;
this.longitude = -98.5795;
this.placeid = "ChIJMS2FahDQzRIRcJqX_aUZCAQ";
//set current position
this.setCurrentPosition();
this.mapsAPILoader.load().then(() => {
//How do i set the agm-map here to load the map with the placeid
});
}
private setCurrentPosition() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.zoom = 12;
});
}
}
Run Code Online (Sandbox Code Playgroud)
然后在html文件上我有这样的事情:
<agm-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom">
<agm-marker [latitude]="latitude" [longitude]="longitude"></agm-marker>
</agm-map>
Run Code Online (Sandbox Code Playgroud)
我查看了GOOGLE文档,它看起来像设置你需要这样的地方ID
var request = {
placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4'
};
service = new google.maps.places.PlacesService(map);
service.getDetails(request, callback);
function callback(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
createMarker(place);
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,我不确定map
自从使用以来要传递什么<agm-map>
.
vso*_*oni 10
你可以使用的mapReady
输出属性agm-map
.将您的HTML更改为
<agm-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom" (mapReady)="mapReady($event)">
<agm-marker [latitude]="latitude" [longitude]="longitude"></agm-marker>
</agm-map>
Run Code Online (Sandbox Code Playgroud)
并在组件中定义以下功能.地图准备好后,将调用此函数.
mapReady($event: any) {
// here $event will be of type google.maps.Map
// and you can put your logic here to get lat lng for marker. I have just put a sample code. You can refactor it the way you want.
this.getLatLong('ChIJN1t_tDeuEmsRUsoyG83frY4', $event, null);
}
getLatLong(placeid: string, map: any, fn) {
let placeService = new google.maps.places.PlacesService(map);
placeService.getDetails({
placeId: placeid
}, function (result, status) {
console.log(result.geometry.location.lat());
console.log(result.geometry.location.lng())
});
}
Run Code Online (Sandbox Code Playgroud)
根据您的需要更改/重构此示例代码,以便您可以将值设置为要传递给html的纬度和经度参数.
<agm-marker [latitude]="latitude" [longitude]="longitude"></agm-marker>
Run Code Online (Sandbox Code Playgroud)