Latitude and Longitude with Google Maps

David Carr

Javascript Tutorials HTML PHP & MySQL

Google Maps allows using its service to get map coordinates:

For instance, In your HTML, two fields to store the latitude and longitude 

<input id="latitude" type="text" name="latitude" value="">
<input id="longitude" type="text" name="longitude" value="">

When a postcode is entered use Google Maps to update the latitude and longitude:

<input id="postcode" type="text" name="postcode" value="">

The JS code, note the <?=$apiKey;?> should contain your Google Maps API key.

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<?=$apiKey;?>"></script>
<script type="text/javascript">
    $(document).on('change', '#postcode', function (e) {
        var geocoder = new google.maps.Geocoder();
        var address = this.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();

                //set the value of input elements with an id of latitude and longitude
                document.getElementById("latitude").value = latitude;
                document.getElementById("longitude").value = longitude;
            } 
        });
    });
</script>

 

Read articles directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Copyright © 2006 - 2024 DC Blog - All rights reserved.