我是使用谷歌地图API的新手,但已设法制作它,以便您可以输入两个位置,它将为您创建路线和方向列表。
但是我想尝试这样做,所以你有一个设定点(长/纬度)作为起始位置,你可以输入一个目的地,它会为你创建方向。
这是我到目前为止所做的:
<html>
<head>
<title>Directions to nearby places</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB_MBMV60nG7Il1CNnJbmBUPrQ2kCMihe0&libraries=places&callback=initMap">
</script>
<script type="text/javascript">
var getDirections;
var directionCalculator = new google.maps.DirectionsService();
function initMap() {
getDirections = new google.maps.DirectionsRenderer();
var mySettings = {
minZoomLevel: 20,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("map"),mySettings);
getDirections.setMap(map);
getDirections.setPanel(document.getElementById("DirectionsList"));
}
function calcRoute() {
var start = document.getElementById("Start").value;
var end = document.getElementById("End").value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionCalculator.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
getDirections.setDirections(response);
}
});
}
</script>
</head>
<body onload="initMap()">
<p id="Time"></p>
`<h1>Plan Your route</h1>`
<form>
<input type="submit" value="Reset" onclick="Reset()">
</form>
<p>
<form action="routeDescription" onsubmit="calcRoute();return false;" id="routeForm">
<input type="text" id="Start" value="" placeholder="Start Location">
<input type="text" id="End" value="" placeholder="Destination">
<input type="submit" value="Preview route">
</form>
</p>
<br>
<div id="map" style="height:75%"></div>
<p>
Here is how to get to your location
</p>
<div id="DirectionsList"></div>
<script>
function Reset() {
location.reload();
}
function Time() {
var date = new Date();
var time = date.toLocaleTimeString();
document.getElementById("Time").innerHTML = time;
}
</script>
</body>
</html>
答案 0 :(得分:1)
这样做的一种方法是给ID为“Start”的输入元素赋值,例如:
<input type="text" id="Start" value=" value="Main St, CA">
或者如果你想删除#Start输入元素并且只有一个目的地输入,只需替换它:
var start = document.getElementById("Start").value;
为你的设定点:
var start = "Main St, CA" // or in coordinates
如果您希望原点位于(设备的)当前位置,可以使用navigator.geolocation.getCurrentPosition():
navigator.geolocation.getCurrentPosition(function (location) {
console.log(location.coords.latitude); //here you have the value of lat
console.log(location.coords.longitude);//here you have the value of lng
//use them wisely
//more code
});