2013-07-24 31 views
8

Tôi sử dụng bản đồ google api 3 để lấy thành phố từ tọa độ. Tôi đã đọc ReverseGeocoding nhưng tôi không hiểu cách có giá trị thành phố chính xác từ loại kết quả này: http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=falseLàm thế nào để có được thành phố từ tọa độ?

+0

vậy, câu hỏi của bạn là "Làm thế nào để phân tích cú pháp JSON"? – Raptor

+0

có! Tức là, tôi có thể phân tích mảng bằng JS không? – Tab

+0

xem câu trả lời của tôi .. –

Trả lời

15

Funktion này trả về tên của thành phố được yêu cầu tại lat/long. Như kịch bản này là từ cuối năm 2012. Làm việc tốt cho tôi thời gian đó. Trả về "không xác định" khi API không tìm thấy bất kỳ.

function get_api ($lat, $long) { 
    $get_API = "http://maps.googleapis.com/maps/api/geocode/json?latlng="; 
    $get_API .= round($lat,2).","; 
    $get_API .= round($long,2);   

    $jsonfile = file_get_contents($get_API.'&sensor=false'); 
    $jsonarray = json_decode($jsonfile);   

    if (isset($jsonarray->results[1]->address_components[1]->long_name)) { 
     return($jsonarray->results[1]->address_components[1]->long_name); 
    } 
    else { 
     return('Unknown'); 
    } 
} 

chỉnh sửa: và jquery.

<p id="city"></p> 

<script> 
$(document).ready(function() {  
    // define lat/long 
    var lat = 37.42; 
    var long = -122.08; 

    $.ajax({ 
     type: 'GET', 
     dataType: "json", 
     url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&sensor=false", 
     data: {}, 
     success: function(data) { 
      $('#city').html(data); 
      $.each(data['results'],function(i, val) { 
       $.each(val['address_components'],function(i, val) { 
        if (val['types'] == "locality,political") { 
         if (val['long_name']!="") { 
          $('#city').html(val['long_name']); 
         } 
         else { 
          $('#city').html("unknown"); 
         } 
         console.log(i+", " + val['long_name']); 
         console.log(i+", " + val['types']); 
        } 
       }); 
      }); 
      console.log('Success'); 
     }, 
     error: function() { console.log('error'); } 
    }); 
}); 
</script> 
+0

chú ý đến bình luận của Shivan Raptors mặc dù –

+4

Mã này giả định rằng kết quả mong muốn nằm trong mục nhập address_components thứ 2 của kết quả thứ hai, không có sự đảm bảo nào (hoặc sẽ luôn là ngay cả khi nó hoạt động ngay bây giờ) kết quả mong muốn. Bạn thực sự nên tìm kết quả với [loại] (https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingAddressTypes) của dữ liệu bạn đang tìm kiếm (địa phương: cho biết thành phố hoặc thị trấn chính trị được kết hợp thực thể) và trả lại điều đó. – geocodezip

+0

vì OP không chỉ định ngôn ngữ lập trình, mã PHP của bạn có thể không phù hợp với OP. * sidenote: * 'return' không phải là một hàm, do đó' return 'Unknown'; 'chính xác hơn là – Raptor

2

Trong HTML5 trang chúng ta có thể có được tên thành phố như sau:

<script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script> 
<script> 
     (function() { 

      if(!!navigator.geolocation) { 
       navigator.geolocation.getCurrentPosition(function(position) { 

        var geocoder = new google.maps.Geocoder(); 
        var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); 

        console.log(position.coords.latitude + ', ' + position.coords.longitude); 

        geocoder.geocode({'latLng': geolocate}, function(results, status) { 
        if (status == google.maps.GeocoderStatus.OK) { 
         var result; 
         if (results.length > 1) { 
         result = results[1]; 
         } else { 
         result = results[0]; 
         } 
         //console.log(result); 
         console.log(result.address_components[2].long_name + ', ' + result.address_components[3].long_name); 

        } 
        });  
       }); 
</script> 
Các vấn đề liên quan