我能夠得到google map
的address
但留不住address
我page
爲什麼我無法保留通過谷歌地圖的返回地址
這裏是我的代碼:
title:string;
informationWindowTitle:string;
address:string;
@ViewChild('map') mapElement: ElementRef;
map: any;
geocodeLatLng(lat, lng) {
var geocoder = new google.maps.Geocoder;
var latlng = {
lat: lat,
lng: lng
};
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
//This is yout formatted address
//window.alert(results[0].formatted_address);
console.log(results[0].formatted_address);
this.title = results[0].formatted_address;
this.informationWindowTitle = results[0].formatted_address;
console.log(this.informationWindowTitle);
return results[0].formatted_address;
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
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.geocodeLatLng(position.coords.latitude,position.coords.longitude);
// console.log(this.address);
this.addMarker();
// this.title = this.address;//results[0].formatted_address;
// this.informationWindowTitle = this.address;//results[0].formatted_address;
}, (err) => {
console.log(err);
});
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click',() => {
infoWindow.open(this.map, marker);
});
}
addMarker(){
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: this.map.getCenter()
});
let content = '<h4>Your Current Location!</h4><p>'+this.address+'</p>';
this.addInfoWindow(marker, content);
}
我想要做的是摘錄
geocodeLatLng(lat, lng) {
// this function returns address
}
initializtion 1. loadMap()2. geocodeLatLng()
loadMap(){
this.geolocation.getCurrentPosition().then((position) => {
this.geocodeLatLng(position.coords.latitude,position.coords.longitude); // sending co-ordinates to above function which returns the address
this.addMarker(); // then adding marker
}, (err) => {
console.log(err);
});
}
please refer this for getting
地址:how to get current postion name using google map api
當我分配這些屬性我沒有得到其值
this.title = results[0].formatted_address;
this.informationWindowTitle = results[0].formatted_address;
QUESTION爲什麼?但我能進去function geocodeLatLng()
你的'答案'似乎是'智能'。我有一個問題,我會在哪裏放置上面的'代碼' – EaB
只需導入'ChangeDetectorRef'並將其注入'構造函數'中。 然後像我一樣修復你的'geocodeLatLng(lat,lng)'函數中的代碼 –