Loading...

Latitude and Longitude with Google Maps

David Carr

1 min read - 12th Mar, 2020

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>

 

0 comments
Add a comment