首页 > 解决方案 > 谷歌地图地理编码意外的财产位置

问题描述

我正在尝试为我的 vue.js 应用程序设置地理编码。我没有使用任何第三方库,只有通过 npm 安装的谷歌地图。

调用 geocode 方法时,它会抛出一个错误,指出属性位置是意外的。我试过“位置”、“纬度”、坐标本身等等。经度和纬度来自navigator.geolocation对象。

这是我的设置脚本的一部分:

Vue.component('catalog', require('./components/Catalog'));
Vue.component('address-autocomplete', require('./components/AddressAutoComplete'));
window.googleMapsClient = require('@google/maps').createClient({
    key: "MY_API_KEY"
});

还有我的 Vue 组件:

getLocationFromGeoData() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            this.setLocation,
            this.showError
        );
    } else {
        showLocationError("Geolocation wird nicht unterstützt!");
    }
},
setLocation(position) {
    var self = this;

    this.location.latitude = position.coords.latitude;
    this.location.longitude = position.coords.longitude;

    var latLng = {
        lat: parseFloat(this.location.latitude),
        lng: parseFloat(this.location.longitude)
    };

    googleMapsClient.geocode({'location': latLng}).asPromise()
        .then((response) => {
            self.location.address = results[1].formatted_address;
        }).catch((err) => {
            showLocationError(err);
        });
},

标签: javascriptgoogle-mapsvue.jsgoogle-maps-api-3

解决方案


请注意,您尝试将坐标解析为地址。此过程通常称为反向地理编码。这意味着您必须使用.reverseGeocode(query, callback)方法而不是.geocode(query, callback)方法。

您的代码应更改为类似于

var latLng = {
    lat: parseFloat(this.location.latitude),
    lng: parseFloat(this.location.longitude)
};

googleMapsClient.reverseGeocode({'latlng': latLng}).asPromise()
    .then((response) => {
        self.location.address = results[1].formatted_address;
    }).catch((err) => {
        showLocationError(err);
    });

有关更多详细信息,请查看 Node.js 的 Maps Web Services 客户端库的文档,网址为

https://googlemaps.github.io/google-maps-services-js/docs/GoogleMapsClient.html

我希望这有帮助!


推荐阅读