我在 Angular 应用程序中使用反向地理编码。
需要的脚本在 index.html 中添加
<script async defer src="https://maps.googleapis.com/maps/api/js">
</scrip>
Run Code Online (Sandbox Code Playgroud)
组件文件看起来像这样
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 …Run Code Online (Sandbox Code Playgroud)