2013-10-29 40 views
8

我真的很新手在JS中,很抱歉,我沒有附加我的代碼,因爲我所做的一切 - 來自Google Map Docs的「helloworld」示例。谷歌地圖:實時繪製和更新Polyline

那麼,什麼是問題: 我想根據用戶的當前位置繪製折線。所以,每個google.maps.LatLng()此刻應該有座標。在地圖上應該顯示整個更新的過程,例如每5秒一次。最後,它就像是在地圖上行走的早晨的可視化,就像那樣。

我知道,如何「繪製」地圖,在VAR flightPlanCoordinates []加分,我問一些例子或鏈接,在哪裏可以找到:

  • 怎麼加電流位置到變種flightPlanCoordinates []
  • 如何使所有這些東西在更新的 「活」 模式

感謝您的幫助:)

UPD:

試圖做這樣的東西,但不工作

var path = poly.getPath(); 

var latitude = position.coords.latitude; 
var longitude = position.coords.longitude; 

path.push(new google.maps.LatLng(latitude, longitude)); 

UPD2: 這裏很酷例如,它應該如何http://kasheftin.github.io/gmaps/

+0

你想要做的是調查[HTML5地理定位API](https://developer.mozilla.org/en-US/docs/WebAPI/Using_geolocation) –

+0

試圖做這樣的東西,但不起作用 'var path = poly.getPath(); var latitude = position.coords.latitude; var longitude = position.coords。經度; path.push(new google.maps.LatLng(latitude,longitude)); ' – Rachnog

回答

9

您需要使用新路徑(已用新點更新的路徑)更新多段線:

// get existing path 
var path = poly.getPath(); 
// add new point 
path.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude)); 
// update the polyline with the updated path 
poly.setPath(path); 

代碼片段:(點擊地圖,點添加到折線)

function initialize() { 
 
    var 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 
 
    }); 
 
    var poly = new google.maps.Polyline({ 
 
    map: map, 
 
    path: [] 
 
    }) 
 
    google.maps.event.addListener(map, 'click', function(evt) { 
 
    // get existing path 
 
    var path = poly.getPath(); 
 
    // add new point (use the position from the click event) 
 
    path.push(new google.maps.LatLng(evt.latLng.lat(), evt.latLng.lng())); 
 
    // update the polyline with the updated path 
 
    poly.setPath(path); 
 
    }) 
 
} 
 
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

'function addLatLng(event){ \t var path = poly.getPath(); \t path.push(new google.maps.LatLng(position.coords.latitude,position.coords.longitude)); \t poly.setPath(path); }'不起作用 – Rachnog

+0

@geocodezip感謝隊友救了我的時間:) – Harsha

2

嘗試下面的代碼:

var path = poly.getPath().getArray(); 
path.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude)); 
poly.setPath(path); 
0

截至目前,該API允許您只需將新的LatLng對象推送到path它會在地圖上更新。

由於他們Complex Polyline例子顯示,你可以這樣做:

var path = poly.getPath() 
path.push(latLng) 

哪裏poly爲您google.maps.PolylinelatLng一個google.maps.LatLng