gpt4 book ai didi

javascript - 如何使用地理位置 API 获取城市名称和州名称?

转载 作者:太空宇宙 更新时间:2023-11-04 16:04:40 27 4
gpt4 key购买 nike

我只是想知道它应该是一个可重用的代码,可以使用地理位置检测当前的城市

最佳答案

我创建了一个示例来执行此操作:

var city, state;
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}

//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng);
}

function errorFunction() {
console.log("Geocoder failed");
}

function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
//find country name
for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
//this is the object you are looking for
city = results[0].address_components[i];
break;
}
}
}

for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
state = results[0].address_components[i];
break;
}
}
}
alert(city.long_name +", "+ state.long_name);
} else {
console.log("City name not available");
}
} else {
console.log("Geocoder failed due to: ", status);
}
});
}

function initialize() {
geocoder = new google.maps.Geocoder();
}

document.addEventListener('DOMContentLoaded', function() {
initialize();
}, false);

可在此处找到工作演示 Plnkr

关于javascript - 如何使用地理位置 API 获取城市名称和州名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41976623/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com