2012-09-01 87 views
0

如果我知道它的經度和緯度,我需要一種方法來查找英國位置的郵編。如何從經緯度獲取英國郵政編碼?

例如:

地址:老鹿園,里士滿,大倫敦TW9 2SL,英國

緯度= 51.4691,經度= -0.2963

使用這個信息,我需要一種方法來以編程方式檢索該位置的郵編。

+1

可能重複[如何在谷歌地圖上的地址獲得英國郵政編碼?](http://stackoverflow.com/questions/12211801/how-to-get-uk-zipcode-from-address-in - 谷歌地圖) – 2012-09-01 06:49:32

+0

是的,但如果你明白的問題,請發送回答 – sumit

回答

2

您試圖解決的問題稱爲反向地理編碼。請看Google maps documentation,裏面有例子。它歸結爲一個具有latlng參數的URL,您可以選擇XML或JSON。可能會有很多結果,因此您必須遍歷返回的結構並選擇最合適的結果。

http://maps.googleapis.com/maps/api/geocode/json?latlng=51.4691,-0.2963&sensor=false

實施例的使用利用CURL + JSON。

function getPostcode($lat, $lng) { 
    $returnValue = NULL; 
    $ch = curl_init(); 
    $url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&sensor=false"; 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    $result = curl_exec($ch); 
    $json = json_decode($result, TRUE); 

    if (isset($json['results'])) { 
    foreach ($json['results'] as $result) { 
     foreach ($result['address_components'] as $address_component) { 
      $types = $address_component['types']; 
      if (in_array('postal_code', $types) && sizeof($types) == 1) { 
      $returnValue = $address_component['short_name']; 
      } 
    } 
    } 
    } 
    return $returnValue; 
} 

echo getPostcode(51.4691, -0.2963); 
+0

如何使用此API請定義和經度和緯度已經得到但我只想要郵編,所以請定義 – sumit

+0

@sumit增加了一個例子。 – Adam

+0

你好亞當我想發送我的代碼,請給我你的電子郵件ID我已經使用另一個代碼形式的地址獲得緯度和經度。可以ü可能改變使用代碼 – sumit

0

這不是谷歌地圖的一部分 - 但這裏有一個英國郵政編碼API:

http://www.uk-postcodes.com/api.php

它允許你向它發送一個請求,包括緯度和位置的經度和它將返回該位置的英國郵政編碼。

不知道它是否有效,但值得一試!

0

我已經使用此代碼:如何獲取郵政編碼特殊英國使用此代碼.. 和估計從from_address到to_address的行程時間。

<style> 
    .ui-autocomplete {background-color: white;width: 300px;border: 1px solid #cfcfcf;list-style-type: none;padding-left: 0px} 
    #intro-text{margin:20px 0} 
    #map_canvas {width: 720px;height: 200px;margin-top:20px;clear:both;display:none} 
    #from_box {margin-left:0px} 
    #to_box, #from_box {float:left;margin-left:10px} 
    #img_arrow {float:left;margin:30px 50px 0 50px} 
    #results{margin: 20px 0 10px 0; overflow:hidden} 
    #distance_direct{float:left;width:40%;border:1px solid black;margin-left:60px;height:90px} 
    #distance_road{float:left;width:40%;border-right:1px solid black; border-top:1px solid black; border-bottom:1px solid black;height:90px} 
    .ui-menu-item a {color:black;font-weight:bold;cursor:pointer} 
</style> 
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script> 
<script type="text/javascript"> 

    $(document).ready(function() { 

     var geocoder = new google.maps.Geocoder(); 

     // This function formats numbers by adding commas 
     function numberFormat(nStr,prefix){ 
      var prefix = prefix || ''; 
      nStr += ''; 
      x = nStr.split('.'); 
      x1 = x[0]; 
      x2 = x.length > 1 ? '.' + x[1] : ''; 
      var rgx = /(\d+)(\d{3})/; 
      while (rgx.test(x1)) 
       x1 = x1.replace(rgx, '$1' + ',' + '$2'); 
      return prefix + x1 + x2; 
     } 
      $("#from_address").autocomplete({ 
       //This bit uses the geocoder to fetch address values 
       source: function(request, response) { 
        geocoder.geocode({'address': request.term }, function(results, status) { 
         response($.map(results, function(item) { 
         return { 
          label: item.formatted_address, 
          value: item.formatted_address, 
          //latitude: item.geometry.location.lat(), 
          //longitude: item.geometry.location.lng() 
         } 
        })); 
       }) 
       } 
      }); 
      $("#to_address").autocomplete({ 
       //This bit uses the geocoder to fetch address values 
       source: function(request, response) { 
        geocoder.geocode({'address': request.term }, function(results, status) { 
         response($.map(results, function(item) { 
         return { 
          label: item.formatted_address, 
          value: item.formatted_address, 
          //latitude: item.geometry.location.lat(), 
          //longitude: item.geometry.location.lng() 
         } 
        })); 
       }) 
       } 
      }); 


     $('#get_results').click(function() { 


      if($('#from_address').val() == "" || $('#from_address').val() == "") { 
       $('#results').hide(); 
       $('#map_canvas').hide(); 
       $('#error_msg').show().html('Please make sure you have entered both a "From" and "To" address.'); 
       return; 
      } else { 
       $('#error_msg').hide(); 
      } 

      var location1; 
      var location2; 
      var formatted_from_address; 
      var formatted_to_address 

      $('#crow_dist').empty(); 
      $('#drive_dist').empty(); 

      geocoder.geocode({ 'address': $('#from_address').val() }, function(results, status) { 
       if (status == google.maps.GeocoderStatus.OK) { 
        //location of first address (latitude + longitude) 
        location1 = results[0].geometry.location; 


        formatted_from_address = results[0].formatted_address; 
        $('#from_address').val(formatted_from_address); 

       ////////////////////////////////////////////// 
         geocoder.geocode({ 'address': $('#to_address').val() }, function(results, status) { 
          if (status == google.maps.GeocoderStatus.OK) { 
           //location of first address (latitude + longitude) 
           location2 = results[0].geometry.location; 
           formatted_to_address = results[0].formatted_address; 
           $('#to_address').val(formatted_to_address); 




           var latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,(location1.lng()+location2.lng())/2); 

           var myOptions = { 
            zoom:10, 
            center: latlng, 
            mapTypeId: google.maps.MapTypeId.ROADMAP 
           }; 

           var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

           //Make sure maps shows both markers 
           var southWest = new google.maps.LatLng(location1.lat(),location1.lng()); 
           var northEast = new google.maps.LatLng(location2.lat(),location2.lng()); 
           var bounds = new google.maps.LatLngBounds(southWest,northEast); 

           document.getElementById("lat1").value = southWest; 
           document.getElementById("lat2").value = northEast; 


           map.fitBounds(bounds); 

           // show route between the points 
           directionsService = new google.maps.DirectionsService(); 
           directionsDisplay = new google.maps.DirectionsRenderer({ 
            suppressMarkers: true, 
            suppressInfoWindows: false 
           }); 

           directionsDisplay.setMap(map); 
           var request = { 
            origin:location1, 
            destination:location2, 
            travelMode: google.maps.DirectionsTravelMode.DRIVING 
           }; 

           directionsService.route(request, function(response, status) { 
            if (status == google.maps.DirectionsStatus.OK) { 
             directionsDisplay.setDirections(response); 
             distance = numberFormat(Math.round((response.routes[0].legs[0].distance.value) * 0.000621371192)); 
             $("#drive_dist").html('<div style="font-weight:bold;font-size:1.6em;margin-bottom:5px">' + distance + ' mi.</div><div style="font-style:italic"><a href="directions/?address1='+$('#from_address').val()+'&address2='+$('#to_address').val()+'">Get Directions</a></div>'); 
            } else { 
             $("#drive_dist").html('<div style="font-weight:bold;font-size:1.6em;margin-bottom:5px">Not Available</div>'); 
            } 

            document.getElementById("distance1").value = distance; 
           }); 

           $('#directionsPanel').empty(); 
           directionsDisplay.setPanel(document.getElementById("directionsPanel")); 

           var marker1 = new google.maps.Marker({ 
            map: map, 
            position: location1, 
            title: "From: " + $('#from_address').val() 
           }); 
           var marker2 = new google.maps.Marker({ 
            map: map, 
            position: location2, 
            title: "To: " + $('#to_address').val() 
           }); 
           //DD=$('#from_address').val(); 

           // create the text to be shown in the infowindows 
           var text1 = '<div style="width:100px"><b>From:</b> '+formatted_from_address+'</div>'; 
           var text2 = '<div style="width:100px"><b>To:</b>'+formatted_to_address+'</div>'; 

           // create info boxes for the two markers 
           var infowindow1 = new google.maps.InfoWindow({ 
            content: text1 
           }); 
           var infowindow2 = new google.maps.InfoWindow({ 
            content: text2 
           }); 

           // add action events so the info windows will be shown when the marker is clicked 
           google.maps.event.addListener(marker1, 'click', function() { 
            infowindow1.open(map,marker1); 
           }); 
           google.maps.event.addListener(marker2, 'click', function() { 
            infowindow2.open(map,marker2); 
           }); 



           function toRad(deg) { 
            return deg * Math.PI/180; 
           } 

           // compute distance between the two points 
           var R = 6371; // Radius of the earth in km 
           var dLat = toRad(location2.lat()-location1.lat()); 
           var dLon = toRad(location2.lng()-location1.lng()); 

           var dLat1 = toRad(location1.lat()); 
           var dLat2 = toRad(location2.lat()); 

           var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
             Math.cos(dLat1) * Math.cos(dLat1) * 
             Math.sin(dLon/2) * Math.sin(dLon/2); 
           var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
           var d = (R * c) * 0.621371192; // Distance in miles; 

           $("#crow_dist").html('<div style="font-weight:bold;font-size:1.6em;margin-bottom:5px">' + numberFormat(Math.round(d)) + ' mi.</div><div style="font-style:italic">"As the Crow Flies"</div>'); 
           $('#map_canvas').show(); 

          } else { 
           alert("Geocode for Address 2 was not successful for the following reason: " + status); 
          } 
         }); 
       } else { 
        alert("Geocode for Address 1 was not successful for the following reason: " + status); 
       } 
      }); 
      $('#results').show(); 
     }); 

     if($('#from_address').val() != '' || $('#to_address').val() != '') { 
      $('#get_results').trigger('click'); 
     } 
    }); 

</script> 


<div id="map_canvas"></div> 
相關問題