Get latitude | longitude using address in Goolge Map

Step  1

Include  Google map api with  key and libraries
<script                                                                                                                                                                                                     src=”https://maps.googleapis.com/maps/api/js?key=AIzaSyAzXoaC9OV09c- sTdIWWR1hWzUcJppx_g8&libraries=places”></script>

Step 2

Create div tag for map with id

<div id=”location_map” style=”width:500px; height:500px;”></div>

Step 3

Create Address input field with latitude and longitude

<div>Address</div>
<div><input type=”text” name=”loc_address” id=”loc_address” value=”” style=”width:400px; height:40px;” /> </div>

<div>Latitude</div>
<div> <input type=”text” name=”loc_latitude” id=”loc_latitude” value=”” style=”width:300px; height:40px;” /> </div>

<div>Longitude</div>
<div> <input type=”text” name=”loc_longitude” id=”loc_longitude” value=”” style=”width:300px; height:40px;” /> </div>

Step  4

Include this script

<script>
Location_map();
function Location_map() {

var Loc_map = new google.maps.Map(document.getElementById(‘location_map’), {
center: {lat: 34.8375, lng: -106.2370},
zoom: 10
});
var location_input = (document.getElementById(‘loc_address’));

var autocomplete = new google.maps.places.Autocomplete(location_input);
autocomplete.bindTo(‘bounds’, Loc_map);

var loc_marker = new google.maps.Marker({
map: Loc_map,
anchorPoint: new google.maps.Point(0, -29)
});

autocomplete.addListener(‘place_changed’, function() {

loc_marker.setVisible(false);
var place = autocomplete.getPlace();

if (place.geometry.viewport) {

Loc_map.fitBounds(place.geometry.viewport);
}
else {
Loc_map.setCenter(place.geometry.location);
Loc_map.setZoom(17);
}
loc_marker.setPosition(place.geometry.location);
loc_marker.setVisible(true);

$(‘#loc_latitude’).val(place.geometry.location.lat());
$(‘#loc_longitude’).val(place.geometry.location.lng());

});

}

</script>

Step  5

when  type in address field,  address will be loaded automatically and latitude and longitude will be placed in input fields for searching address.

 

Completed

Leave a Reply

Your email address will not be published. Required fields are marked *