我是 javascript 的非常非常初学者。 我正在构建一个应用程序并决定实现一些地理定位功能,主要是向用户显示他当前的位置。 我做到了,但我的函数返回完整的地址(如街道、号码、社区、城市、邮政编码和国家/地区) 这就是到目前为止所做的...
/* CURRENT LOCATION */
function geolocationSuccess(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latlng = {lat: latitude, lng: longitude};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]){
var user_address = results[0].formatted_address;
document.getElementById("current_location").innerHTML = user_address;
}else {
console.log('No results found for these coords.');
}
}else {
console.log('Geocoder failed due to: ' + status);
}
});
}
function geolocationError() {
console.log("please enable location for this feature to work!");
}
$(document).ready(function() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
} else {
alert("Geolocation not supported!");
}
});
如何获取并仅显示城市?
最佳答案
因为您要返回完整地址:
var user_address = results[0].formatted_address;
相反,您需要遍历地址组件并找到地点
:
var user_city = results[0].address_components.filter(ac=>~ac.types.indexOf('locality'))[0].long_name
数据结构如下所示:https://developers.google.com/maps/documentation/geocoding/intro
关于javascript - 如何从地理编码器中仅获取城市名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56598417/