Перетащить маркер google maps
Доброго времени суток.
Есть необходимость поставить лишь одну метку на карту с возможностью перетаскивания. Т.е. пользователь ставит местоположение кликом по карте, затем можно перетащить маркер на нужное место. После клика на карту в поле с id="map_coordinates" показываются координаты X и Y местоположения. Вопрос как поставить обработчик на "перетаскивание" (drag) маркера? П.с. карта находится в id="map-canvas", координаты в id="map+coordinates". Заранее благодарен за помощь Html: <div class="map_field"> <div id="map_coordinates"></div> <div id="map-canvas"></div> </div> javascript:
function initialize() {
var Riga = new google.maps.LatLng(56.9496487,24.1051864);
var mapOptions = {
zoom: 13,
center: Riga,
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
marker = new google.maps.Marker({});
google.maps.event.addListener(map, "click", function(event) {
deleteMarkers();
addMarker(event.latLng);
});
/// Здесь возникли проблемы
google.maps.event.addListener(marker, "drag", function(event) {
// alert('drag');
$('#map_coordinates').empty().append(location.e+' '+location.d);
});
}
var image = 'http://google-maps-icons.googlecode.com/files/beach-nudist.png';
// Add a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
draggable:true,
icon:image,
map: map
});
markers.push(marker);
$('#map_coordinates').empty().append(location.e+' '+location.d);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
// Sets the map on all markers in the array.
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setAllMap(null);
}
// Shows any markers currently in the array.
function showMarkers() {
setAllMap(map);
}
|
Пробовал так, тогда функция вызывается при движении карты:
google.maps.event.addListener(map, "drag", function(event) {
alert('drag');
$('#map_coordinates').empty().append(location.e+' '+location.d);
});
Может кто знает как сделать чтобы функция срабатывала по передвижению маркера? П.с. пробовал в месте map писать marker и markers, не сработало. |
Неужели никто не сталкивался с этим вопросом?
|
Цитата:
![]() Цитата:
какой API ? если третья версия, то смотреть здесь : https://developers.google.com/maps/d...ript/reference |
melky, спасибо за отзыв.
Версия v3, доку смотрел. 1. Мне нужно по клику на карту поставить маркер и передать его значения в #map_coordinates 2. Если передвинуть маркер, то обновить его координаты в #map_coordinates С первым проблем нет, передвинуть маркер тоже можно. Не получается вызвать функцию по событию "drag". Вот не могу понять, проблема в использовании неправильного обьекта( map, marker или markers), который передвигаю или в неправильном событии (использовал drag, dragstart, dragend) или проблема и там и там? |
Цитата:
глядите в пример http://jsbin.com/dibo/1 я думаю, поймёте, что к чему :) вот ссылки: события: https://developers.google.com/maps/d...eference#event методы класса Marker: https://developers.google.com/maps/d...ference#Marker |
Огромное спасибо, melky.
Если кому интересно, то сделал так:
var map;
function initialize() {
var city= new google.maps.LatLng(0.000000 ,00.000000);
var mapOptions = {
zoom: 13,
center: city,
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var marker = new google.maps.Marker({
position: city,
draggable:true,
icon:image,
map: map,
animation: google.maps.Animation.DROP,
});
google.maps.event.addListener(map, "click", function(event) {
position_x = event.latLng.lat();
position_y = event.latLng.lng();
marker.setPosition(event.latLng);
$('#map_coordinates').empty().append(position_x+' '+position_y);
});
google.maps.event.addListener(marker,"dragend", function(event) {
position_x = marker.getPosition().lat();
position_y = marker.getPosition().lng();
$('#map_coordinates').empty().append(position_x+' '+position_y);
});
// gdsgsdgdsgsg
}
var image = 'http://google-maps-icons.googlecode.com/files/beach-nudist.png';
// Add a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
draggable:true,
icon:image,
map: map,
});
markers.push(marker);
$('#map_coordinates').empty().append(location.e+' '+location.d);
}
// Sets the map on all markers in the array.
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setAllMap(null);
}
// Shows any markers currently in the array.
function showMarkers() {
setAllMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
|
| Часовой пояс GMT +3, время: 01:41. |