I am making a google maps 开发者_运维知识库application in which i allow a user to place only one marker on the map by clicking on the map. Everytime the user click again on the map, the old marker is deleted and the marker is placed on the new click location. I have a hidden input field and i want the its value to change each time the marker changes position. This value should be the coordinates of the new marker location. The code i have written for this is as follows,
var map;
var marker;
var coords;
function initialize() {
var latlng = new google.maps.LatLng(19.074448,72.872314);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
};
function placeMarker(location) {
if (marker) {
marker.setMap(null);
marker = null;
placeMarker(location);
}
else {
marker = new google.maps.Marker({
position: location,
map: map
});
document.getElementById("id_lat").value = marker.getPosition().toUrlValue()
}
};
Specifically, i am using this line to change the value,
document.getElementById("id_lat").value = marker.getPosition().toUrlValue()
where the id of the relevant hidden field is "id_lat" This doesn't seem to work though. What am i doing wrong and how do i fix it ? I am new to javascript.
I think you forgot to add your one marker at initialize() function. Other than that your code seems to work fine.
var map;
var marker;
var coords;
function initialize() {
var latlng = new google.maps.LatLng(19.074448,72.872314);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
// add a marker on map
placeMarker(latlng);
};
function placeMarker(location) {
if (marker) {
marker.setMap(null);
marker = null;
placeMarker(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map
});
document.getElementById("id_lat").value = marker.getPosition().toUrlValue();
// worked for me for <input type="text" value="Submit" id="id_lat" style="display:none"/> element
alert(document.getElementById("id_lat").value);
}
};
精彩评论