2012-05-01 45 views
0

我曾尝试过几种方法使用地理定位方法获取访问者国家/地区的位置,但仍无济于事。谷歌地图API - 获取用户地址

有人可以帮助atall,因为我想要访问国家并使用ajax将其写入数据库。

我当前的代码

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script> 
<script> 
    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(){ 
    alert("Geocoder failed"); 
} 

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



    } 

    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) { 
     console.log(results) 
     var country = results[7].formatted_address; 
     $('.location').text(country); 
     var dataStrings = 'email=<?php echo $userid;?>&location='+ country; 
     console.log(dataStrinsg); 
     $.ajax({ 
     type: "POST", 
     url: "location-update.php", 
     data: dataStrings, 
     success: function() { 
      location.reload(); 
      } 
     }); 
     return false; 
     if (results[1]) { 
     //formatted address 
     // alert(results[0].formatted_address) 
     //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_1") { 
        //this is the object you are looking for 
        city= results[0].address_components[i]; 
        break; 
       } 
      } 
     } 
     //city data 
     alert(city.short_name + " " + city.long_name) 


     } else { 
      alert("No results found"); 
     } 
     } else { 
     alert("Geocoder failed due to: " + status); 
     } 
    }); 
    }</script> 
+0

您可以指向代码的实时运行版本,或者放置一个我们可以运行的JSFiddle?除了没有上下文的最简单代码之外,很难调试所有代码。 –

回答

0

假设你的地理编码之前调用initalize()(否则geocode是不确定的):

你在这里访问results[7]

var country = results[7].formatted_address; 

..但不保证results[7]存在。

+0

initalize加载了身体标记。 现在Initalize正在运行,它会在警告框中弹出“Geocoder failed”:/ – ngplayground