Google Maps API V3: 通过邮编获取经纬度 Get Location (Latitude and Longitude) from Zip Cod

In this article I will explain with an example, how to get Location Coordinates i.e. Latitude and Longitude from Zip Code (Pin Code) by making use of Google Maps API V3 (Version 3) and JavaScript.
Google Maps API V3: 通过邮编获取经纬度 Get Location (Latitude and Longitude) from Zip Code (Pin Code) using JavaScript
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <textarea id="txtAddress" rows="3" cols="25"></textarea>
    <br />
    <input type="button" onclick="GetLocation()" value="Get Location" />
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    <!--
        function GetLocation() {
            var geocoder = new google.maps.Geocoder();
            var address = document.getElementById("txtAddress").value;
            geocoder.geocode({ 'address': address }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    var latitude = results[0].geometry.location.lat();
                    var longitude = results[0].geometry.location.lng();
                    alert("Latitude: " + latitude + "nLongitude: " + longitude);
                } else {
                    alert("Request failed.")
                }
            });
        };
        //-->
    </script>
</body>
</html>
 
Explanation
I have made use of HTML <textarea> for allowing user enter the address of a location and an HTML button which will trigger the process of fetching the Latitude and Longitude using the Google Maps API.
As soon as the button is clicked the JavaScript click event handler is raised which executes the JavaScript function GetLocation which makes call to the Google Maps API which in turn returns the Latitude and Longitude based on the address provided for the location.
 
Note: Here I have not specified the API Key but you need to get one from the Google Maps API V3 in order to use on hosted server.
 
 

你可能感兴趣的:(api,Google,maps)