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>

 

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.