2012-09-01 3 views
0

위도와 경도를 알고있는 경우 영국 위치의 우편 번호를 찾는 방법이 필요합니다. 예를 들어위도와 경도에서 영국 우편 번호를받는 방법은 무엇입니까?

:

주소 : 올드 사슴 공원, 리치몬드, 그레이터 런던 TW9 2SL, 영국

나는 방식을 필요로이 정보를 사용하여 위도 = 51.4691, 경도 = -0.2963

프로그래밍 방식으로 해당 위치의 우편 번호를 검색합니다.

+1

가능한 중복 [구글 맵에서 주소에서 영국 우편 번호를 얻는 방법?] (http://stackoverflow.com/questions/12211801/how-to-get-uk-zipcode-from-address-in -google-map) –

+0

네,하지만 질문을 이해하면 대답을 보내주세요. – sumit

답변

2

해결하려는 문제를 역 지오 코딩이라고합니다. 예제를 제공하는 Google maps documentation을 살펴보십시오. 그것은 latlng 매개 변수가있는 URL로 귀결됩니다. XML 또는 JSON을 선택할 수 있습니다. 많은 결과가있을 수 있으므로 반환 된 구조를 반복하고 가장 적절한 것을 선택해야합니다. CURL + JSON을 사용하여

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

사용 예제.

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

hello adam 나는 내 코드를 보내고 싶다. 나는 이미 다른 코드 양식 주소를 사용하여 위도와 경도를 사용하고있다. use code – 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> 
관련 문제