📅  最后修改于: 2023-12-03 15:38:41.939000             🧑  作者: Mango
如果你正在使用谷歌地图 API JS,有时你可能只想获取地图上显示的城市名称,而不需要其他地理信息(如坐标,街道名称等)。这篇文章将介绍如何仅获取城市名称。
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.7749, lng: -122.4194},
zoom: 8
});
}
map.addListener('center_changed', function() {
//code here
});
var geocoder = new google.maps.Geocoder;
var center = map.getCenter();
geocoder.geocode({'location': center}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
var city = null;
for (var i = 0; i < results[0].address_components.length; i++) {
var types = results[0].address_components[i].types;
if (types.indexOf('locality') !== -1) {
city = results[0].address_components[i].long_name;
break;
}
}
console.log(city);
} else {
console.log('No results found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.7749, lng: -122.4194},
zoom: 8
});
map.addListener('center_changed', function() {
var geocoder = new google.maps.Geocoder;
var center = map.getCenter();
geocoder.geocode({'location': center}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
var city = null;
for (var i = 0; i < results[0].address_components.length; i++) {
var types = results[0].address_components[i].types;
if (types.indexOf('locality') !== -1) {
city = results[0].address_components[i].long_name;
break;
}
}
console.log(city);
} else {
console.log('No results found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
});
}
通过 Geocoder API 将坐标转换成城市名称,我们可以在谷歌地图 API JS 中仅获取城市名称。这样做可能会使你的代码更加高效。