Get Latitude / Longitude by Address using JavaScript.

Hello Developers,

Today I am going to show you how to get automatically Latitude and Longitude via address. Here you can find quick code for the Get Latitude / Longitude by putting Address

Please follow my below steps:

Step 1: Put below js in the head section of your PHP file.

<script src="https://maps.googleapis.com/maps/api/js?key=<Put_your_Google_api_key_here>&libraries=places"></script>

<script type="text/javascript">
    function initialize() {
        var input = document.getElementById('searchTextField');
        var autocomplete = new google.maps.places.Autocomplete(input);
        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            document.getElementById('city2').value = place.name;
            document.getElementById('mlat').value = place.geometry.location.lat();
            document.getElementById('mlang').value = place.geometry.location.lng();
            });
    }
    google.maps.event.addDomListener(window, 'load', initialize); 
</script>
* From above code Put_your_Google_api_key_here should be replaced by Your Google Api Key.


Step 2: Create simple HTML form in file. For that use my below code.

<form method="post" action="#">
<label><b>Map Address</b></label>
 <input type="text" name="maddress" id="searchTextField" class="form-control"  required="required" size="100" autocomplete="on" runat="server" />
  <br />
  <input type="hidden" id="city2" name="city2" size="100" />
  <br />
  <label><b>Map Lat</b> </label>
  <input type="text" id="mlat"   name="mlat”   class="form-control" required="required" size="100" />
  <br />
  <label><b>Map Lang</b> </label>
  <input type="text" id="mlang" name="mlang" class="form-control"  required="required" size="100" />
  <br />
  <input type="submit" id="submit" class="btn" />
</form>

Result

You can also see result in below video

Thank you 🙂

Blog Catagory : Blog