我的Google地图标记存在问题。这是我的代码:
var map;
var geocoder;
var current;
var styles = [
{
stylers: [
{ hue: "#00c0eb" },
{ saturation: -10 }
]
},{
featureType: "road",
elementType: "geometry",
stylers: [
{ lightness: 100 },
{ visibility: "simplified" }
]
},{
featureType: "road",
elementType: "labels",
stylers: [
{ visibility: "on" }
]
}
];
var NewEventMarker;
function changeMarkerPosition(marker, ll) {
marker.setPosition(ll);
}
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
panControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.BOTTOM_CENTER
},
scaleControl: false,
streetViewControl: false
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
map.setOptions({styles: styles});
google.maps.event.addListener(map, 'click', addNewEvent);
}
function codeAddress() {
var address = "London";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var image = new google.maps.MarkerImage("/img/markers/user-m.png",
new google.maps.Size(32.0, 49.0),
new google.maps.Point(0, 0),
new google.maps.Point(16.0, 24.0)
);
var marker = new google.maps.Marker({
map: map,
icon: image,
flat: false,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function addNewEvent(event){
var NEMlatLng;
if(NewEventMarker == undefined){
NewEventMarker = new google.maps.Marker({
map: map,
draggable: true,
icon: "/img/markers/marker-add.png",
position: event.latLng,
title: "Добавить событие"
});
} else {
changeMarkerPosition(NewEventMarker, event.latLng);
}
google.maps.event.addListener(NewEventMarker,'dragend',function(event) {
alert(event.latLng);
});
}
此代码的想法是当用户点击地图,启动工作函数 - addNewEvent时,如您所见,如果已存在“NewEventMarker”,它只是将此标记移动到用户点击的位置,并且如果没有标记,则会创建。因此,如果您尝试我的代码,您可以看到,如果我在地图上单击,例如两次或三次,标记将移动,但是当我拖动我的标记时,启动分配给'dragend'事件的工作功能。但是它会多次使用,我点了多少地图。我该如何解决?
当我尝试将google.maps.event.addListener(NewEventMarker,'dragend'.......)添加到我的代码中的其他地方时出现错误:无法读取属性'_ e3 '未定义 请帮帮我;)
答案 0 :(得分:1)
Evgeny,你做的几乎一切正确,但每次点击都会附加dragend
的新事件处理程序。因此,您有多个dragend
个事件,并且每个事件都有一个警报。
解决方案是将事件处理程序移动到if
语句并仅在创建NewEventMarker
的情况下添加事件侦听器(仅限第一次):
function addNewEvent(event){
var NEMlatLng;
if (NewEventMarker == undefined){
NewEventMarker = new google.maps.Marker({
map: map,
draggable: true,
icon: "marker-add.png",
position: event.latLng,
title: "Добавить событие"
});
google.maps.event.addListener(NewEventMarker, 'dragend', function(event) {
alert(event.latLng);
});
} else {
changeMarkerPosition(NewEventMarker, event.latLng);
}
}