2012-09-09 45 views
1

我正在使用一些有用的代碼,我在http://exploregooglemaps.blogspot.com.br/2012/02/measuring-distance-with-markers.html處找到了添加標記並測量距離的代碼。可拖動捕捉到道路距離標記

我希望默認情況下標記可以捕捉到道路,但是當用戶按住shift鍵時會使用直線。

我已經設法實現了shift鍵的if語句,並且當我按住Shift鍵時繪製了一條路徑,但默認情況下沒有繪製路徑路徑。

我調用兩個功能,一是畫直線drawPath和一個劃出一道捕捉到的分道線drawPathD

任何幫助將非常感激。

<code> 
var map, 
service = new google.maps.DirectionsService(), 
shiftPressed = false, 
poly; 

var path = []; 

shiftPressed = false; 
var markers = []; 
var routePoints = []; 

google.maps.event.addDomListener(document, "keydown", function() { 
shiftPressed = true; 
}); 
google.maps.event.addDomListener(document, "keyup", function() { 
shiftPressed = false; 
}); 

function $(id) { 
return document.getElementById(id); 
} 

var map; 
var mapOptions = { 
center: new google.maps.LatLng(-23.5489433, - 46.6388182), 
zoom: 15, 
mapTypeId: google.maps.MapTypeId.ROADMAP 
}; 

var markers = []; 
var line; 

function initialize() { 
map = new google.maps.Map($("map_canvas"), mapOptions); 
line = new google.maps.Polyline({ 
map: map, 
strokeColor: "#FF3333", 
strokeOpacity: 0.5, 
strokeWeight: 8 
}); 

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


if (shiftPressed) { 

markers.push(marker); 
drawPath(); 

} else { 

markers.push(marker); 
drawPathD(); 

} 


google.maps.event.addListener(marker, 'dblclick', function (event) { 
marker.setMap(null); 
drawPath(); 
}); 

google.maps.event.addListener(marker, 'drag', function (event) { 
drawPath(); 
}); 
}); 
} 

function countMarkers() { 
count = 0; 
for (var i = routePoints.length - 1; i >= 0; i--) { 
if (markers[i].getMap() == null) { 
routePoints.splice(i, 1); 
} else { 
count++; 
} 
} 
return count; 
} 

function drawPath() { 
countMarkers(); 

var coords = []; 
for (var i = 0; i < markers.length; i++) { 
coords.push(markers[i].getPosition()); 
} 
line.setPath(coords); 

meters = google.maps.geometry.spherical.computeLength(coords); 
$("distKm").value = Math.round(meters/1000 * 100)/100; 
$("distMi").value = Math.round(meters/1609 * 100)/100; 
} 

function drawPathD(event) { 
countMarkers(); 
var coords = []; 

service.route({ 
origin: path[path.length - 1], 
destination: event.latLng, 
travelMode: google.maps.DirectionsTravelMode.WALKING 
}, function (result, status) { 
if (status == google.maps.DirectionsStatus.OK) { 
path = path.concat(result.routes[0].overview_path); 
routePoints.setPath(path); 
} 
}); 



meters = google.maps.geometry.spherical.computeLength(coords); 
$("distKm").value = Math.round(meters/1000 * 100)/100; 
$("distMi").value = Math.round(meters/1609 * 100)/100; 
} 

function clearMarkers() { 
for (var i = 0; i < markers.length; i++) { 
markers[i].setMap(null) 
} 
drawPath(); 
} 
google.maps.event.addDomListener(window, 'load', initialize); 

</code> 

回答