How to dynamically get the marker location in google map?


#1

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>


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



<input type="text" id="searchmap" name ="Location" placeholder="Enter the Location"><br>
<div id="map-canvas"></div>


<input type="text" class="form-control input-sm" name="lat" id="lat">


<input type="text" class="form-control input-sm" name="lng" id="lng">



<script>
  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    center:{
      lat: 12.971599,
      lng: 77.594563
    },
    zoom:15
  });
  var marker = new google.maps.Marker({
    position: {
      lat: 12.971599,
      lng: 77.594563
    }, 
    map: map,
    draggable: true
  });

  var searchBox = new google.maps.places.SearchBox(document.getElementById('searchmap'));
  google.maps.event.addListener(searchBox,'places_changed',function(){
    var places = searchBox.getPlaces();
    var bounds = new google.maps.LatLngBounds();
    var i,place;
    for(i=0; place=places[i]; i++){
      bounds.extend(place.geometry.location);
      marker.setPosition(place.geometry.location);
    }
    map.fitBounds(bounds);
    map.setZoom(15);
  });

  google.maps.event.addListener(marker,'position_changed',function(){
    var lat = marker.getPosition().lat();
    var lng = marker.getPosition().lng();
    $('#lat').val(lat);
    $('#lng').val(lng);
  });
</script>

#2

Hi @gitnaveena,

Thanks for your Google Maps JavaScript API code.

Would you be willing to also supply us with some HTML and CSS to accompany the script, in order to make it easier for users to try it out? You don't need to supply an API key with it. Instead, users could copy your code, and then either open it on their local machine or add their own API key to it.


#3

@appylpye Thanks for the suggestion , I have posted my code with HTML


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.