I have given google map and have given two text box for latitude and longitude. Currently when running the application Google map and marker is visible. But my problem is that when clicking or dragging the marker the changed latitude and longitude is not visible in the text box. And showing a java script error that marker is not defined.
I recreated your setup and here are a few things that you can do:
Add a callback param when you call the Google Maps Javascript API. And please DO NOT post your API KEY here or any public area where anyone can just abuse it.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=YOUR_API_KEY&callback=initMap"
Change the window.onload to the named callback function initMap
and also include your listener there. This is so that when we fetch the Google Maps Javascript API, it will call initMap()
right after making sure your Maps object will not be left undefined.
function initMap() {
//map..
var map = new google.maps.Map(document.getElementById('dvMap'), {
center: {
lat: 10.9968683,
lng: 76.00882
},
zoom: 15
});
//marker..
var marker = new google.maps.Marker({
position: {
lat: 10.9968683,
lng: 76.00882
},
map: map,
draggable: true
});
//dragend event of marker
google.maps.event.addListener(marker,'dragend', function () {
var Lats = marker.getPosition().lat();
var Longs = marker.getPosition().lng();
$('#Lat').val(Lats);
$('#Long').val(Longs);
});
}
Here's a working sample without using Razor syntax so you can see it work alone:
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
</head>
<body>
<div id="dvMap" style="height:250px;"></div>
<input type="text" id="Lat">
<input type="text" id="Long">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap" async defer></script>
<script type="text/javascript">
function initMap() {
//map..
var map = new google.maps.Map(document.getElementById('dvMap'), {
center: {
lat: 10.9968683,
lng: 76.00882
},
zoom: 15
});
//marker..
var marker = new google.maps.Marker({
position: {
lat: 10.9968683,
lng: 76.00882
},
map: map,
draggable: true
});
//dragend event of marker
google.maps.event.addListener(marker,'dragend', function () {
var Lats = marker.getPosition().lat();
var Longs = marker.getPosition().lng();
$('#Lat').val(Lats);
$('#Long').val(Longs);
});
}
</script>
</body>
</html>
Here's an external link showing how it might work in a .NETFiddle Ignore the controller and model.
Hope this helps!