如何从纬度和经度获得英国邮政编码?

时间:2012-09-01 06:09:01

标签: php google-maps

如果我知道它的纬度和经度,我需要一种方法来查找英国位置的邮政编码。

例如:

地址:Old Deer Park,Richmond,Greater London TW9 2SL,United Kingdom

纬度= 51.4691,经度= -0.2963

使用此信息,我需要一种以编程方式检索该位置的邮政编码的方法。

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

它不是谷歌地图的一部分 - 但这里有一个英国邮政编码API:

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

它允许您向其发送包括一个位置的纬度和经度的请求,它将返回该位置的英国邮政编码。

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

答案 2 :(得分: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>