DEV Community

David Carr
David Carr

Posted on • Originally published at dcblog.dev on

Latitude and Longitude with Google Maps

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="">
Enter fullscreen mode Exit fullscreen mode

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

<input id="postcode" type="text" name="postcode" value="">
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)