2012-05-01 24 views
0

Iveはジオロケーションメソッドを使用して訪問者の国の場所を取得するためにいくつかの方法を試しましたが、無駄な時間はありません。Google Map API - ユーザーの住所を取得

訪問国を取得し、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はbodyタグでロードされます。 Initalizeを実行すると、アラートボックスに「Geocoder failed」がポップアップ表示されます。/ – ngplayground

関連する問題