我在这篇文章中找到了一些代码:How can I get the country and region code using geolocation instead of full country and region names
我想获取用户的 iso 国家代码(2 位数字)。
但我不明白为什么它不起作用?在 chrome 控制台中,我在第 40 行收到“;uncaught SyntaxError: Unexpected token ;”
jsfiddle:http://jsfiddle.net/M9kzT/
<script>
var region = "";
var country = "";
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition,noGeolocation);
} else {
console.log('nope');
}
}
function showPosition(position)
{
var geocoder = new google.maps.Geocoder();
var latlong = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
geocoder.geocode({'latLng': latlong}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results[0].address_components.length; i++)
{
var longname = results[0].address_components[i].long_name;
var type = results[0].address_components[i].types;
if (type.indexOf("administrative_area_level_1") != -1)
{
region = longname;
}
if (type.indexOf("country") != -1)
{
country = short_name;
}
}
}
});
}
}
function noGeolocation()
{
console.log('nope2');
}
getLocation();
</script>
最佳答案
您有 2 个 }
放错地方:缺少一个,一个不是必需的:
function showPosition(position) {
var geocoder = new google.maps.Geocoder();
var latlong = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
geocoder.geocode({'latLng': latlong}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results[0].address_components.length; i++) {
var longname = results[0].address_components[i].long_name;
var type = results[0].address_components[i].types;
if (type.indexOf("administrative_area_level_1") != -1) {
region = longname;
}
if (type.indexOf("country") != -1) {
country = short_name;
}
}
}
}
});
}
///}
更新:更改了函数showPosition()
以记录长短国家名称:
function showPosition(position) {
var geocoder = new google.maps.Geocoder();
var latlong = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
geocoder.geocode({'latLng': latlong}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results[0].address_components.length; i++) {
var longname = results[0].address_components[i].long_name;
var types = results[0].address_components[i].types;
for (var typeIdx = 0; typeIdx < types.length; typeIdx++) {
if (types[typeIdx] == 'country') {
console.log(results[0].address_components[i].long_name);
console.log(results[0].address_components[i].short_name);
}
}
}
}
}
});
}
关于javascript - 使用 google api 进行反向查找来获取 iso 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21814609/