maps-api-v3
当今最常用的API之一是Geolocation API。 地理位置允许应用程序确定您的物理坐标,并为您量身定制应用程序。 这有可能极大地改善您的用户体验。 本文将向您展示如何与Google Maps API一起使用Geolocation API。
Google Maps API可让您将Google Maps服务与您的网站集成。 本文中的示例使用API版本3.10。 该服务是完全免费的,但是您应该订阅API控制台网站以获得API密钥,并在向该服务发送请求时使用它。 如果您需要有关如何获取密钥的信息,请阅读入门指南 。 API密钥可让您监视应用程序的使用情况,并在必要时为Google提供与您联系的机会。 请记住,Google Maps API有使用限制 ,您可以付费增加使用限制 。 本文还假设您对地理定位有基本的了解,可以通过阅读使用HTML5地理定位API来获得。
Google Maps API概述
本部分介绍了Google Maps API的主要类和方法。 还有许多其他对象和方法可用,但是讨论API的各个方面超出了本文的范围。 该库中最重要和最常用的类是google.maps.Map
。 Map
类接受两个参数,它们是一个HTML元素(将包含地图)和一个google.maps.MapOptions
对象 。 MapOptions
对象具有许多属性,但是仅需要以下三个属性。
-
center
:google.maps.LatLng
对象(稍后会详细介绍),用于设置初始地图中心。 -
mapTypeId
:google.maps.MapTypeId
对象,用于设置地图的类型。 例如,您可以将地图查看为道路地图还是卫星地图。 -
zoom
:一个正数,用于设置地图的初始缩放比例。
除了用于类属性的几个设置方法和获取方法外,还有几种值得一提的方法。 第一个是fitBounds()
,它将LatLngBounds
对象作为其唯一参数。 LatLngBounds
表示通过指定西南和东北点构建的矩形。 这会将地图的视图设置为包含给定范围。 第二种方法是panTo()
,它接受LatLng
对象并更改地图的中心。
另一个重要的类是google.maps.LatLng
,它表示纬度和经度的地理坐标。 几乎所有Maps API的方法都使用此类。 例如,我们将使用它来使地图在用户的位置上居中。 但是,它们还用于跟踪路线或在地图上绘制折线。
许多地图包含指定兴趣点(例如目的地)的标记。 要将标记放置在地图上,您必须使用google.maps.Marker
类。 它将使用传递给构造函数的选项(一个google.maps.MarkerOptions
对象)创建一个标记,并将其应用于指定的地图。 唯一需要的选项是position
,它设置标记的位置。
在向您展示示例之前,我将介绍的最后一个类是Geocoder
。 它使您可以从地址转换为LatLng
对象,反之亦然。 它有一个空的构造函数,只有一个方法geocode()
,它使用GeocoderRequest
对象作为参数,还有一个回调函数,您将在其中读取结果。
一个基本的例子
使用上述几个类,您现在就可以编写一个简单但不错的应用程序。 这个例子不是很难理解,但是仍然使用所有讨论的类和方法。 该示例检索用户的位置,并使用地图上的标记进行显示。 Geocoder
服务用于检索用户的完整地址,并将其显示在页面上。 我们还将使用检索到的位置的accuracy
参数在该位置周围绘制一个蓝色圆圈。
使用Maps API的第一步是实际包含它。 这非常简单,只需将以下行添加到您的网页即可。
<script src="http://maps.google.com/maps/api/js?key=YOUR-KEY-GOES-HERE&sensor=true"></script>
由于Google Maps仍然可以在没有密钥的情况下工作,并且为了避免示例中的冗长行,只需编写以下内容即可。
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
请注意,这两行都包含一个sensor
参数。 必须将其包含在URL中,如果您使用的是传感器(如GPS),则将其设置为true
否则将其设置为false
。 您可以在加载Maps API上了解更多信息。
为了构建示例,我们将使用两个函数。 第一个使用用户的位置来创建地图并在用户周围绘制一个圆圈。 第二个功能查询Google以根据其位置检索用户的地址。 让我们看看两者的关键点。
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
这条简单的线使用Position
对象的纬度和经度来创建LatLng
对象。 我们将在函数的其余部分中使用该对象。 实际上,它将在MapOptions
用于设置我们正在构建的Map
的中心。 作为地图的容器,我将使用<div>
元素,其ID为map
。
var myOptions = {
zoom : 16,
center : userLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
}
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
现在是时候将标记添加到地图上,以表明用户的位置了。 我们将使用Google Maps默认图标,但是您可以使用icon
属性或setIcon()
方法指定所需的图像。
new google.maps.Marker({map: mapObject, position: userLatLng });
此时,您可以关闭该功能,并使用一个带有简单标记的地图来显示用户位置。 但是,由于在桌面环境中精度可能非常低,因此可视化它会很好。 您可能会猜到,我们将使用Circle
类来完成此操作,该类将在地图上绘制一个圆。 它具有许多用于设置颜色,不透明度,半径等的属性,但是最重要的属性是其应用的地图对象。
var circle = new google.maps.Circle({
center: userLatLng,
radius: position.coords.accuracy,
map: mapObject,
fillColor: '#0000FF',
fillOpacity: 0.5,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
mapObject.fitBounds(circle.getBounds());
请注意,最后一条语句使用从圆上获取的边界调用fitBounds()
方法。 这样做是为了确保如果圆超出缩放视图的范围,则地图将相应缩小以显示整个圆。
第二个函数名为writeAddressName()
,它使用LatLng
对象并设置location
属性以查询Geocoder
服务。 在回调函数中,我们将测试是否发生错误。 如果确实发生错误,将显示该错误。 否则,将显示格式化的地址。
function writeAddressName(latLng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": latLng
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
document.getElementById("address").innerHTML = results[0].formatted_address;
else
document.getElementById("error").innerHTML += "Unable to retrieve your address" + "<br />";
});
}
全部放在一起
给定上一节中显示的代码,最终且完全可用的代码如下所示。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Geolocation and Google Maps API</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>
function writeAddressName(latLng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": latLng
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
document.getElementById("address").innerHTML = results[0].formatted_address;
else
document.getElementById("error").innerHTML += "Unable to retrieve your address" + "<br />";
});
}
function geolocationSuccess(position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Write the formatted address
writeAddressName(userLatLng);
var myOptions = {
zoom : 16,
center : userLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
// Place the marker
new google.maps.Marker({
map: mapObject,
position: userLatLng
});
// Draw a circle around the user position to have an idea of the current localization accuracy
var circle = new google.maps.Circle({
center: userLatLng,
radius: position.coords.accuracy,
map: mapObject,
fillColor: '#0000FF',
fillOpacity: 0.5,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
mapObject.fitBounds(circle.getBounds());
}
function geolocationError(positionError) {
document.getElementById("error").innerHTML += "Error: " + positionError.message + "<br />";
}
function geolocateUser() {
// If the browser supports the Geolocation API
if (navigator.geolocation)
{
var positionOptions = {
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
};
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError, positionOptions);
}
else
document.getElementById("error").innerHTML += "Your browser doesn't support the Geolocation API";
}
window.onload = geolocateUser;
</script>
<style type="text/css">
#map {
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<h1>Basic example</h1>
<div id="map"></div>
<p><b>Address</b>: <span id="address"></span></p>
<p id="error"></p>
</body>
</html>
结论
本文介绍了Google Maps API中最重要的类的几种方法和属性。 此外,我们已经展示了如何将它们与Geolocation API一起使用,以构建完整的功能服务,以跟踪用户的位置并在地图上定位它们。 当然,您可以做更多的事情,这将在下篇有关该惊人API的文章中看到。
翻译自: https://www.sitepoint.com/working-with-geolocation-and-google-maps-api/
maps-api-v3