0

I have created a function to add the marker when there is no marker on map or remove the original marker and added a new one to replace it. However, i can add the first part of script successfully to add the marker on map. however, the original marker can not be removed and new marker could not added when i click the map again. Can anyone suggest what is the problem?

/*Create a listener to record the Click event of the google map and define it as the starting point (i.e. Origin in Google Direction
service*/
google.maps.event.addListener(map, 'click', function(event) {
  if (origin == null) {
    origin = event.latLng;

    lat = origin.lat();
    lng = origin.lng();
    UpdateLatLng();  

    var startimage = 'images/Start4.png';
    StartMarker = new google.maps.Marker({
         map: map,
         position: origin,
         icon: startimage
     });
  } else {
 //Relocate the Starting point and assign the new position to Textbox
    alert ("The starting point was relocated on screen"); 
    StartMarker.setMap(null);
    directionsDisplay.setMap(null);
    directionsDisplay.setPanel(null);
    directionsDisplay.setDirections({routes: []});
    var origin = event.latLng;  
    lat = origin.lat();
    lng = origin.lng();
    UpdateLatLng(); 
    var startimage = 'images/Start4.png';
    StartMarker = new google.maps.Marker({
         map: map,
         position: origin,
         icon: startimage
     });
    } 
}); 
4

2 回答 2

0

尝试使用现有的Marker类似:

// Will change the poisition
StartMarker.setPosition(origin); 
// Will change the Icon
StartMarker.setIcon(startimage);
于 2013-05-12T08:46:25.763 回答
0

这对我有用:

var StartMarker = null;
/*Create a listener to record the Click event of the google map and define it as the starting point (i.e. Origin in Google Direction
service*/
google.maps.event.addListener(map, 'click', function(event) {
  if (!StartMarker) {
    origin = event.latLng;
    lat = origin.lat();
    lng = origin.lng();

    StartMarker = new google.maps.Marker({
         map: map,
         position: origin
     });
  } else {
 //Relocate the Starting point and assign the new position to Textbox
    alert ("The starting point was relocated on screen"); 
    StartMarker.setMap(null);
    var origin = event.latLng;  
    lat = origin.lat();
    lng = origin.lng();
    StartMarker = new google.maps.Marker({
         map: map,
         position: origin
     });
    } 
}); 

工作示例

于 2013-05-12T14:11:22.437 回答