2

我有以下代碼,允許用戶點擊地圖上的某個地方,並記錄他們點擊的任何位置的GPS位置。它在後端正常工作,但每當用戶點擊多次時,它會在地圖上留下多個標記。它始終保持最後的位置,所以它可以工作,但對於不知道後端正在發生什麼的用戶而言,這有點令人困惑。是否有一些小技巧可以讓我們做到這一點,以便每當用戶點擊創建一個新標記時,舊標記將被刪除?允許用戶一次只創建一個Google地圖標記

代碼:

var map; 
var GPSlocation; 


function initialize() { 
    var haightAshbury = new google.maps.LatLng(37.7699298, -93.4469157); 
    var mapOptions = { 
    zoom: 4, 
    center: haightAshbury, 
    mapTypeId: google.maps.MapTypeId.TERRAIN 
    }; 
    map = new google.maps.Map(document.getElementById("map"), mapOptions); 

    google.maps.event.addListener(map, 'click', function(event) { 
    addMarker(event.latLng); 
    }); 
} 

function addMarker(location) { 
//I save the location right here 
    GPSlocation = location; 
    document.getElementById("GPSlocation").value = GPSlocation; 
    marker = new google.maps.Marker({ 
    position: location, 
    map: map 
    }); 
} 

回答

3

做標記一個全局變量通過聲明它的功能外:

var marker; 
function addMarker(location) { 
    GPSlocation = location; 
    document.getElementById("GPSlocation").value = GPSlocation; 
    marker = new google.maps.Marker({ 
     position: location, 
     map: map 
    }); 
} 

您也可以使之更有效率僅更新標記的位置,而不是創建一個新對象:

var marker; 
function addMarker(location) { 
    GPSlocation = location; 
    document.getElementById("GPSlocation").value = GPSlocation; 
    if (!marker) { 
     marker = new google.maps.Marker({ 
      position: location, 
      map: map 
     }); 
    } else { 
     marker.setPosition(location); 
    } 
} 
+0

嗯,我確實做到了,但由於某些原因,地圖甚至不會呈現現在...我會嘗試和調試在早晨 – exployre

+0

@exployre你可能想出來,但有我的第二個例子中存在一個錯誤,現在它已被糾正。 – doublesharp

6

只要使用方法google.maps.Marker例如:

var map, 
    GPSlocation, 
    marker; // <-- Added 

// ... snip ... 

function addMarker(location) { 
    // ... snip ... 
    if (!marker) { 
     // Create the marker if it doesn't exist 
     marker = new google.maps.Marker({ 
     position: location, 
     map: map 
     }); 
    } 
    // Otherwise, simply update its location on the map. 
    else { marker.setPosition(location); } 
} 
相關問題