在使用地理定位和Google Maps API中,您学习了如何确定用户的实际位置并将其显示在地图上。 在此后续文章中,您将创建一个服务,该服务可使用户获取从一个地址到另一个地址的路线。 为了增强用户体验,该服务还将允许用户自动使用其当前位置作为起点。
本文假设读者已经熟悉了从内容以前的帖子 。 话虽如此–让我们开始吧。
进一步探索Google Maps API
在演示中,您将重新认识旧朋友Map
, LatLng
和Geocoder
。 您还将结交一些新朋友。 第一个是google.maps.DirectionsService
,它计算两个或多个位置之间的方向(或路线)。 这个课很简单。 它的构造函数不带参数,只有一个方法route()
,它可以计算路线。 此方法接受两个参数,一个google.maps.DirectionsRequest
对象和一个回调函数。
google.maps.DirectionsRequest
对象用于设置路由请求必须满足的选项。 该对象唯一需要的属性是origin
, destination
和travelMode
。 前两个属性定义路径的起点和终点,而travelMode
定义交通方式。 可能的值包括骑自行车,开车,步行和公交(使用公共交通工具)。 需要注意的重要一件事是, origin
和destination
可以使用LatLng
实例或包含地址的字符串。
如我所说,请求中还可以包含几个选项,例如unitSystem
,要求使用特定的单位系统返回距离。 可能的值为公制( google.maps.UnitSystem.METRIC
)和英制( google.maps.UnitSystem.IMPERIAL
)。 默认值是根据原产国选择的。 您还可以使用waypoints
属性指定一组要通过的中间点。 此外,您可以约束方向。 例如,如果可能,可以通过将属性avoidHighways
设置为true
来请求不使用高速公路的路线。 您还可以通过将avoidTolls
属性设置为true
来尝试避开收费公路。
DirectionsService
的回调函数返回两个值,一个google.maps.DirectionsResult
对象和google.maps.DirectionsStatus
类的可能值之一(实际上是属性)。 前者只有一个属性routes
,它是DirectionsRoute
的数组,其中包含每个计算出的路径的信息。 DirectionsStatus
表示请求的最终状态,并且可以指示成功( DirectionsStatus.OK
),无结果( DirectionsStatus.ZERO_RESULTS
)或错误(如DirectionsStatus.INVALID_REQUEST
或DirectionsStatus.REQUEST_DENIED
)。
我们的另一个新朋友是google.maps.DirectionsRenderer
类。 它呈现一个的形式检索的方向
DirectionsResult
从检索对象DirectionsService
。
该类仅包含getter和setter,因此我们将不再对其进行进一步的探讨。
唯一值得注意的是它的构造函数,该构造函数接受
google.maps.DirectionsRendererOptions
对象,该对象允许您设置多个选项。后者的关键性质是
directions
和map
,即设置为显示(使用检索到的路线DirectionsService
)和用来显示路线地图对象。
让我们开始编码
现在您已经看到了本文中使用的所有新类,是时候深入研究代码了。 为了使用户能够请求从起点到目的地的路径,您需要的第一件事是表格。 这将非常简单,因为它只需要两个<input>
元素和一个Submit按钮。 但是,为了增强用户体验,该页面还将提供机会以用户的当前位置自动填充<input>
。 为了实现此目标,我将在每个<input>
下方放置一个链接,单击该链接后,将使用Geolocation和Google Maps API检索用户的地址。 实现此功能的表格如下所示。
<form id="calculate-route" name="calculate-route" action="#" method="get">
<label for="from">From:</label>
<input type="text" id="from" name="from" required="required" placeholder="An address" size="30" />
<a id="from-link" href="#">Get my position</a>
<br />
<label for="to">To:</label>
<input type="text" id="to" name="to" required="required" placeholder="Another address" size="30" />
<a id="to-link" href="#">Get my position</a>
<br />
<input type="submit" />
<input type="reset" />
</form>
现在,我们将继续进行演示背后的业务逻辑。 与第一篇文章不同,我们将利用jQuery快速选择DOM中的元素,并以跨浏览器的方式附加处理程序。 由于所有工作都是在客户端完成的,因此我们需要做的第一件事是阻止表单的默认行为,并运行一些我们稍后将介绍的其他JavaScript。 为了实现此目标,我们将处理程序附加到表单的submit
事件。 处理程序使用jQuery preventDefault()
方法,然后调用calculateRoute()
函数。 实现它的代码如下所示。
$("#calculate-route").submit(function(event) {
event.preventDefault();
calculateRoute($("#from").val(), $("#to").val());
});
最重要的代码包含在calculateRoute()
函数中。 该函数将接受两个参数from
和to
,分别代表起点和终点地址。 第一步是创建map
实例,如以下代码所示。
// Center initialized to Naples, Italy
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(40.84, 14.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
在我们进行下一步之前,我想讨论一些注意事项。 如您所见,我使用静态位置将地图初始居中。 正如您在上一篇文章中了解到的那样, center
属性是必需的。 在此演示中,您可能会忽略它,因为如果路由请求成功,则将重新绘制地图并相应地居中。 您不应该这样做,因为如果请求失败,您将看到一个灰色填充区域。 一种替代方法是根据用户的当前位置初始将地图居中。 这需要额外的地理位置查找,因此您可能会认为这是浪费资源。
接下来,您需要创建DirectionsService
实例和directionsRequest
对象,如下所示。 该演示仅使用unitSystem
选项,但您可以进一步扩展。
var directionsService = new google.maps.DirectionsService();
var directionsRequest = {
origin: from,
destination: to,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
};
最后一步是使用route()
方法运行请求。 我们还必须编写回调函数,该函数使用响应来设置和显示计算出的路径。 在回调函数中,我们将检查请求是否成功,在这种情况下,我们将显示路由,在这种情况下,我们将显示错误。 这由下面的代码实现。
directionsService.route(
directionsRequest,
function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
new google.maps.DirectionsRenderer({
map: mapObject,
directions: response
});
}
else
$("#error").append("Unable to retrieve your route<br />");
}
);
全部放在一起
上一节解释了该演示的关键组成部分。 现在,是时候将这些片段放到最终结果中了,如下所示。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Find a route using Geolocation and Google Maps API</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function calculateRoute(from, to) {
// Center initialized to Naples, Italy
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(40.84, 14.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
var directionsService = new google.maps.DirectionsService();
var directionsRequest = {
origin: from,
destination: to,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
};
directionsService.route(
directionsRequest,
function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
new google.maps.DirectionsRenderer({
map: mapObject,
directions: response
});
}
else
$("#error").append("Unable to retrieve your route<br />");
}
);
}
$(document).ready(function() {
// If the browser supports the Geolocation API
if (typeof navigator.geolocation == "undefined") {
$("#error").text("Your browser doesn't support the Geolocation API");
return;
}
$("#from-link, #to-link").click(function(event) {
event.preventDefault();
var addressId = this.id.substring(0, this.id.indexOf("-"));
navigator.geolocation.getCurrentPosition(function(position) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
$("#" + addressId).val(results[0].formatted_address);
else
$("#error").append("Unable to retrieve your address<br />");
});
},
function(positionError){
$("#error").append("Error: " + positionError.message + "<br />");
},
{
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
});
});
$("#calculate-route").submit(function(event) {
event.preventDefault();
calculateRoute($("#from").val(), $("#to").val());
});
});
</script>
<style type="text/css">
#map {
width: 500px;
height: 400px;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Calculate your route</h1>
<form id="calculate-route" name="calculate-route" action="#" method="get">
<label for="from">From:</label>
<input type="text" id="from" name="from" required="required" placeholder="An address" size="30" />
<a id="from-link" href="#">Get my position</a>
<br />
<label for="to">To:</label>
<input type="text" id="to" name="to" required="required" placeholder="Another address" size="30" />
<a id="to-link" href="#">Get my position</a>
<br />
<input type="submit" />
<input type="reset" />
</form>
<div id="map"></div>
<p id="error"></p>
</body>
</html>
结论
本文向您介绍了Google Maps API中的几个新类和属性。 您使用这些类开发了一种基本服务,该服务允许用户获取从一个地址到另一个地址的路线。 在下一篇文章中,您将学习如何创建折线以连接地图上的多个点。
From: https://www.sitepoint.com/find-a-route-using-the-geolocation-and-the-google-maps-api/