I’ve managed to add markers to a Google Map on click, but now I need to update an <input> field inside a form each time a new marker is placed. So, when a new marker is placed, the input in question is updated with the latitude and longitude of the marker.
I’m using Google Maps Javascript API v3.
Here’s my Javascript:
<script type="text/javascript">
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(39.47860556892209,-3.328857421875),
zoom: 7,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
google.maps.event.addListener(map, 'click', function(event) {
//NEITHER OF THESE 2 OPTIONS WORK
cambiarMarker(event.latLng);
//document.getElementById("lat").value = event.latLng.lat();
//document.getElementById("lng").value = levent.latLng.lng();
document.forms['insertData'].lati.value = location.lat();
document.forms['insertData'].long.value = location.lng();
});
var markerActual;
function cambiarMarker(location) {
//CREATES AND PUT THE NEW MARKER
}
downloadUrl("phpsqlajax_genxml2.php", function(data) {
//GETS INFO FROM AN XML THAT IS CREATED FROM THE DATABASE WITH PHP
}
function bindInfoWindow(marker, map, infoWindow, html) {
//BINDS INFORMATION WINDOW WITH THE XML INFO
}
function downloadUrl(url, callback) {
//GET THE XML FILE
}
function parseXml(str) {
//PARSES FROM THE XML
}
function doNothing() {}
</script>
And here’s my HTML:
<body onload="load()">
Aqui debería salir algo
<div id="map" style="width: 500px; height: 300px"></div>
<form name="insertData" action="insertar_datos.php" method="post">
Nombre: <input type="text" name="name"><br>
Dirección: <input type="text" name="address"><br>
Latitud: <input type="text" name="lati" id="lat"><br> <!--HERE'S INPUT1-LATITUDE-->
Longitud: <input type="text" name="long" id="lng"><br> <!--HERE'S INPUT2-LONG-->
Teléfono de contacto: <input type="text" name="telefono"><br>
Comentario: <textarea name="comentario"></textarea><br>
<input type="submit" value="Enviar">
</form>
</body>
In principle you could also handle
changeevent on the input field and set the coordinates of the marker. This is what I’m doing in my application. And also I handle thedragevent of a marker and change the coordinates during dragging. In this case handle bothdraganddragendevents of a marker! Thedragendyou MUST handle, thedragnot so but it is cool to let the coordinates change as you drag the marker 🙂The change event of input field can be handled e.g. this way (using jquery, supposing markup like
<input id="coords"...):