【发布时间】:2018-05-30 21:47:40
【问题描述】:
我在 Angular 应用程序中使用反向地理编码。
需要的脚本添加在index.html中
<script async defer src="https://maps.googleapis.com/maps/api/js">
</scrip>
组件文件是这样的
import { Component } from '@angular/core';
declare const google: any;
export class MapComponent {
lat;
lng;
address;
constructor() {
this.locate();
}
public locate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
position => {
this.lat = position.coords.latitude; // Works fine
this.lng = position.coords.longitude; // Works fine
let geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(this.lat, this.lng);
let request = {
latLng: latlng
};
geocoder.geocode(request, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0] != null) {
this.address = results[0].formatted_address; //<<<=== DOES NOT WORK, when I output this {{ address }} in the html, it's empty
console.log(this.address); //<<<=== BUT here it Prints the correct value to the console !!!
} else {
alert("No address available");
}
}
});
},
error => {
console.log("Error code: " + error.code + "<br /> Error message: " + error.message);
}
);
}
}
}
在组件的html文件中,应该是输出地址
<div>{{ lat }}</div> // Works fine
<div>{{ lng }}</div> // Works fine
<div>{{ address }}</div> // Deosn't Work, EMPTY
但它总是空的, 但是这一行
console.log(this.address);
打印出正确的值。
【问题讨论】:
-
谢谢,您的代码帮助我启动了我的地理编码器!
标签: angular google-maps-api-3 geocoding reverse-geocoding