Aaron Sterling Aaron Sterling - 7 months ago 35
Javascript Question

Google maps api get lat and lng dynamically

When I run my code, the map doesn't display. I am working on my localhost. I want to put lat and lng to inputs. Then when I change the lat and lng the inputs will change dynamically. How can I solve this problem?

<!DOCTYPE html>
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id="googleMap" style="width:500px;height:500px;"></div>
Lat: <input type="text" id="lat"><br>
Lng: <input type="text" id="lng">
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(41,28);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("googleMap"), myOptions);
addMarker(myLatlng, 'Default Marker', map);
map.addListener('click',function(event) {
addMarker(event.latLng, 'Click Generated Marker', map);
);
}}
function addMarker(latlng,title,map) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: title,
draggable:true
});
marker.addListener('drag',function(event) {
$('#lat').val() = event.latLng.lat();
$('#lng').val() = event.latLng.lng();
});
marker.addListener('dragend',function(event) {
$('#lat').val() = event.latLng.lat();
$('#lng').val() = event.latLng.lng();
});}
</script>
</body></html>

Answer

You have some bugs in your code.. and you are not calling the function initialize(). Try this updated code

<!DOCTYPE html>
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id="googleMap" style="width:500px;height:500px;"></div>
Lat: <input type="text" id="lat"><br>
Lng: <input type="text" id="lng">
<script type="text/javascript">
function initialize() {
    var myLatlng = new google.maps.LatLng(41,28);
    var myOptions = {
      zoom: 15, 
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("googleMap"), myOptions);
    addMarker(myLatlng, 'Default Marker', map);
    map.addListener('click',function(event) {
        addMarker(event.latLng, 'Click Generated Marker', map);
    });
}
function addMarker(latlng,title,map) {
    var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: title,
            draggable:true
    });
    marker.addListener('drag',function(event) {
         $('#lat').val(event.latLng.lat())  ;
        $('#lng').val(event.latLng.lng())  ;
    });
    marker.addListener('dragend',function(event) {
        $('#lat').val(event.latLng.lat())  ;
        $('#lng').val(event.latLng.lng())  ;
    });
}
initialize();
</script>
</body></html>