點擊起點和終點, 做路徑規劃作業
之前的作業: 點擊起點和終點, 做路徑規劃,
也是卡一陣子才寫出來@@
完整code如下:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map-點兩點做路徑規劃作業</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="result"></div>
<script>
var map;
var geocoder;
var directions;
var count = 0;
var uOrigin;
var uDestination;
var marker1;
var marker2;
var routeHistory;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 23, lng: 120},
zoom: 8
});
google.maps.event.addListener(map, "click", function(e) {
count++;
if (count === 1) {
uOrigin = e.latLng;
marker1 = new google.maps.Marker({
position: e.latLng,
map: map
});
} else if (count === 2) {
uDestination = e.latLng;
marker2 = new google.maps.Marker({
position: e.latLng,
map: map
});
directions = new google.maps.DirectionsService();
directions.route({
origin: uOrigin,
destination: uDestination,
travelMode: google.maps.TravelMode.TRANSIT
}, function(result) {
routeHistory = new google.maps.DirectionsRenderer({
directions: result,
map: map,
panel: document.getElementById("result")
});
marker1.setMap(null);
marker2.setMap(null);
});
} else {
count = 0;
marker1.setMap(null);
marker2.setMap(null);
if (routeHistory !== null) {
routeHistory.setMap(null);
}
return;
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
async defer></script>
</body>
</html>
留言
張貼留言