2016-01-07 56 views
-2

我正在尋找一種功能,即當用戶單擊標記時出現,然後當用戶單擊下一個標記時,它將使用一條線將它連接到上一個標記。我曾嘗試使用谷歌api文檔,但似乎無法使該功能工作。誰能幫忙?使用一條線將標記鏈接在一起:google maps api

下面是代碼:

google.maps.event.addListener(map, "click", function(event) { 
var marker = new google.maps.Marker({ 
     position: event.latLng, 
     map: map 
    }); 

    poly = new google.maps.Polyline({ 
    strokeColor: '#000000', 
    strokeOpacity: 1.0, 
    strokeWeight: 3 
    }); 
    poly.setMap(map); 

    map.addListener('click', addLatLng); 
    } 

    function addLatLng(event) { 
    var path = poly.getPath(); 

    path.push(event.latLng); 

    var marker = new google.maps.Marker({ 
    position: event.latLng, 
    title: '#' + path.getLength(), 
); 
+0

我看不到任何在您的代碼中添加[google.maps.Polyline](https://developers.google.com/maps/documentation/javascript/shapes#polylines)的嘗試,您做了什麼嘗試你認爲應該工作?請提供一個[最小,完整,已測試和可讀的示例](http://stackoverflow.com/help/mcve)來證明這一嘗試。 – geocodezip

+0

我編輯了問題以顯示我使用的代碼,它沒有加載地圖,因爲錯誤控制檯顯示「Uncaught SyntaxError:missing」)在參數列表「adn也」後未捕獲的ReferenceError:初始化沒有定義「但我不確定如何解決這個 –

+0

添加缺少的「)」。您發佈的代碼遠非「完整」。您從未設置折線的路徑屬性。 – geocodezip

回答

1

最簡單的辦法是使折線全球性的,然後做addLatLng事件處理函數內的一切:

// global polyline 
var map; 
var poly = new google.maps.Polyline({ 
    strokeColor: '#000000', 
    strokeOpacity: 1.0, 
    strokeWeight: 3 
}); 

// add marker and point to polyline path 
function addLatLng(event) { 
    var path = poly.getPath(); 
    path.push(event.latLng); 
    var marker = new google.maps.Marker({ 
    position: event.latLng, 
    title: '#' + path.getLength(), 
    map: map 
    }); 
}; 

代碼片段:

// global variables 
 
var map; 
 
var poly = new google.maps.Polyline({ 
 
    strokeColor: '#000000', 
 
    strokeOpacity: 1.0, 
 
    strokeWeight: 3 
 
}); 
 

 
function initialize() { 
 
    map = new google.maps.Map(
 
    document.getElementById("map_canvas"), { 
 
     center: new google.maps.LatLng(37.4419, -122.1419), 
 
     zoom: 13, 
 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
 
    }); 
 
    map.addListener('click', addLatLng); 
 
    // add the polyline to the map 
 
    poly.setMap(map); 
 
} 
 

 
function addLatLng(event) { 
 
    var path = poly.getPath(); 
 
    path.push(event.latLng); 
 
    var marker = new google.maps.Marker({ 
 
    position: event.latLng, 
 
    title: '#' + path.getLength(), 
 
    map: map 
 
    }); 
 
}; 
 
google.maps.event.addDomListener(window, "load", initialize);
html, 
 
body, 
 
#map_canvas { 
 
    height: 100%; 
 
    width: 100%; 
 
    margin: 0px; 
 
    padding: 0px 
 
}
<script src="https://maps.googleapis.com/maps/api/js"></script> 
 
<div id="map_canvas"></div>

+0

那是我在例子中使用的代碼,我說我工作,但是當我將代碼放入代碼中用於說明infowindows,代碼根本不起作用 –

+0

我的答案中的代碼與您的代碼中的代碼不同題。如果您無法將其添加到您的代碼中,請按照我在第一條評論中的要求提供一個[最小,完整,測試和可讀的示例](http://stackoverflow.com/help/mcve)來說明問題。 – geocodezip