Google Map API - 获取用户地址

时间:2012-05-01 12:13:25

标签: javascript ajax google-maps geolocation

我已经尝试了几种使用地理定位方法获取访问者国家/地区位置的方法,但是暂时没有用。

有人可以帮助我,因为我想获取访问国家/地区并使用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>

1 个答案:

答案 0 :(得分:0)

假设您在地理编码之前致电initalize()(否则将geocode未定义):

您在此处访问results[7]

var country = results[7].formatted_address;

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