Skip to content Skip to sidebar Skip to footer

How Can I Use One Marker For Multiple Functions

I'm trying to make a geocoding function and reverse geocoding function in the same html page. I need to use just one marker for these functions. The code below works but every time

Solution 1:

Within your codeAddress() function you'll need to check if marker exists and then create it if it doesn't or simply set it's position if it doesn't.

To do this, you'll first need to declare a global variable for marker in the same way you currently do for geocoder and map.

Then modify the block of code that creates the marker to the following:

if(marker){
    marker.setPosition(results[0].geometry.location);
}else{
    marker=new google.maps.Marker({
        map:map,
        position:results[0].geometry.location,
        draggable:true
    });
    google.maps.event.addListener(marker,"dragend",function(){
        lat=marker.getPosition().lat();
        document.getElementById("latitude").value=lat;
        lg=marker.getPosition().lng();
        document.getElementById("longitude").value=lg ;
    });
}

EDIT: You'll also need to do something similar within your codeLatLng() function.

ASIDE: Incidentally, you should remove the marker's dragend function within your initialize function.

Solution 2:

Instead of creating a marker every time, create it once, store it in a global variable, and then check that variable to see if the marker already exists.

If it doesn't, create it, if it does, then just call setPosition(lat,lng) on the global variable.

EDIT: This answer purposely does not include any code, but an accurate description of how to solve the issue

Post a Comment for "How Can I Use One Marker For Multiple Functions"