我在这篇文章中找到了一些代码:How can I get the country and region code using geolocation instead of full country and region names
我想获取用户iso国家代码(2位数)。
但我无法弄清楚为什么它不起作用?在chrome上的控制台中,我得到了“;未被捕获的SyntaxError:Unexpected token;”第40行
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>
答案 0 :(得分: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);
}
}
}
}
}
});
}