gmaps.min.js
Google Maps has proved to be a highly successful Google service, incorporating a range of invaluable tools such as Street View, Route Planning and Google Traffic. Many companies and organizations rely on Google Maps to provide their services – and it’s thanks to the Google Maps API that they’re able to do so.
事实证明,谷歌地图是一项非常成功的Google服务,它结合了一系列宝贵的工具,例如街景 , 路线规划和Google交通 。 许多公司和组织都依靠Google Maps提供服务-这要归功于Google Maps API的支持。
Google introduced the Google Maps API in 2005. This allowed developers to create custom applications with Maps. Google subsequently launched APIs for Android and iOS application development.
Google在2005年引入了Google Maps API 。这使开发人员可以使用Maps创建自定义应用程序。 Google随后启动了用于Android和iOS应用程序开发的API。
As useful as the Maps APIs are, they take a bit of knowhow to utilize. That’s where GMaps.js comes in. GMaps.js is an open-source, MIT-licence JavaScript library. Written by Gustavo Leon, GMaps aims to simplify the original Google Maps JavaScript API. It takes care of the extensive API code and provides appropriate methods to deal with Maps. It’s cleaner, more concise and hence easier to use.
尽管与Maps API一样有用,但它们需要一些技巧来利用。 那就是GMaps.js的源代码。GMaps.js是一个开放源代码的MIT许可证JavaScript库。 由Gustavo Leon撰写的GMaps旨在简化原始的Google Maps JavaScript API。 它会处理大量的API代码,并提供处理Maps的适当方法。 它更干净,更简洁,因此更易于使用。
In this article, we’ll look at map components like Markers, Polygons and Overlays. We’ll also discuss Static Maps, and the use of Geolocation and Geocoding to operate on a user’s location. All of this will be in reference to GMaps. It helps you create map applications with easy-to-use methods. I’ve used it to create a sample application (Mapit), which I’ll discuss further at the end of the article.
在本文中,我们将研究诸如Markers,Polygons和Overlays之类的地图组件。 我们还将讨论静态地图,以及使用Geolocation和Geocoding对用户的位置进行操作。 所有这些都将参考GMaps。 它可以帮助您使用易于使用的方法来创建地图应用程序。 我用它来创建一个示例应用程序( Mapit ),在本文结尾处将对此进行进一步讨论。
The example below is from the original Documentation Page. The code (JavaScript only) loads a map with its center at latitude -34.397 and longitude 150.644, with a zoom-level of 8:
以下示例来自原始文档页面 。 代码(仅适用于JavaScript)加载地图,其中心位于纬度-34.397和经度150.644 ,缩放级别为8 :
var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); }map is the HTML element id where the map will load.
map是将加载mapHTML元素ID。
We can write the same basic app with GMaps like this:
我们可以使用GMaps编写相同的基本应用程序,如下所示:
new GMaps({ el: '#map', lat: -34.397, lng: 150.644, zoom: 8 });This tutorial will guide you through some of the most used components in maps, with example Pens to demonstrate each.
本教程将指导您完成一些地图上最常用的组件,并使用Pen实例进行演示。
Create a basic HTML page and add a reference to the Maps API. You need to include the GMaps Library too. So go to GMaps and download gmaps.js. Include it in your web page and you’re good to go.
创建一个基本HTML页面,并添加对Maps API的引用。 您还需要包括GMaps库。 因此,转到GMaps并下载gmaps.js 。 将其包含在您的网页中,一切顺利。
<!doctype html> <html> <head> <style> #map { width: 400px; height: 400px; } </style> </head> <body> <div id="map"></div> <!-- Google Maps JS API --> <script src="https://maps.googleapis.com/maps/api/js"></script> <!-- GMaps Library --> <script src="gmaps.js"></script> <script> /* Map Object */ var mapObj = new GMaps({ el: '#map', lat: 48.857, lng: 2.295 }); </script> </body> </html>This is a rudimentary page that I’ll reference in the example snippets below. The Map Object will be modified in some of these examples.
这是一个基本页面,我将在下面的示例片段中引用该页面。 在某些示例中,将修改Map对象。
The Maps API offers various components for customizing maps. The same components can be added with GMaps with less code.
Maps API提供了用于自定义地图的各种组件。 可以用更少的代码将相同的组件添加到GMaps中。
A change in the HTML DOM (document object model) can be described as an event. You can call a function on the occurrence of specific events over the map (like a double-click or a mouseover). The following snippet defines functions for click and zoom_changed events:
HTML DOM(文档对象模型)中的更改可以描述为一个事件。 您可以在地图上发生特定事件时调用函数(例如双击或鼠标悬停)。 以下代码段定义了click和zoom_changed事件的功能:
var mapObj = new GMaps({ el: '#map', lat: 48.857, lng: 2.295, click: function(e) { alert('You clicked on the map'); }, zoom_changed: function(e) { alert('You zoomed the map'); } });You can add other events if you like. A list of all map events is provided in the Events section in the documentation. Some of the useful ones are:
您可以根据需要添加其他事件。 文档的“ 事件”部分提供了所有地图事件的列表。 一些有用的是:
EventDescriptiondblclickDouble mouse clickmouseoverMouse enters mapmouseoutMouse exits mapdragMap is draggedrightclickRight mouse click 事件 描述 dblclick 双击鼠标 mouseover 鼠标进入地图 mouseout 鼠标退出地图 drag 地图被拖动 rightclick 鼠标右键Example Pen
示例笔
A marker is a locator on a map. It’s generally shown as a balloon hanging over the marked location. GMaps offers the addMarker() method to add a marker. It accepts an object literal with the following properties for the marker:
标记是地图上的定位器。 通常将其显示为悬挂在标记位置上的气球。 GMaps提供了addMarker()方法来添加标记。 它接受具有以下标记属性的对象文字:
lat: Latitude
lat :纬度
lng: Longitude
lng :经度
title: Title displayed on mouseover
title :鼠标悬停时显示的标题
icon: Custom image for the marker
图标 :标记的自定义图像
details: Custom object with extra data
详细信息 :具有额外数据的自定义对象
infoWindow: Information about the marker
infoWindow :有关标记的信息
Of these, it’s mandatory to assign values to lat and lng, while the others are optional. The value of infoWindow should be another object. This object itself has the following properties:
其中,必须为lat和lng分配值,而其他则是可选的。 infoWindow的值应该是另一个对象。 该对象本身具有以下属性:
content: HTML content
内容 :HTML内容
maxWidth: Maximum width for the window. If not set, window spans length of the text inside it.
maxWidth :窗口的最大宽度。 如果未设置,则窗口跨越其中的文本长度。
infoWindow supports some more options.
infoWindow支持更多选项 。
This snippet is a valid example of addMarker():
此代码段是addMarker()的有效示例:
var m = mapObj.addMarker({ lat: 48.8583701, lng: 2.2944813, title: 'Eiffel Tower', infoWindow: { content: '<h4>Eiffel Tower</h4><div>Paris, France</div>', maxWidth: 100 } });addMarker() also accepts events – for example, a marker reacting to mouseover event:
addMarker()也接受事件-例如,标记对mouseover事件做出React:
mapObj.addMarker({ lat: 48.8583701, lng: 2.2944813, mouseover: function(e) { alert('Triggered'); } });Example Pen
示例笔
A marker can be removed using the removeMarker() method. Pass the marker object to it (m in our case) as an argument:
可以使用removeMarker()方法删除标记。 将标记对象作为参数传递给它(在本例中为m ):
mapObj.removeMarker(m);removeMarkers() collectively removes all the markers associated with the map object.
removeMarkers()共同删除与地图对象关联的所有标记。
mapObj.removeMarkers();To locate any point on a map, you need to have its geographical coordinates (latitude and longitude). Geocoding is calculating these geographical coordinates from a given location address. The geocode() method allows us to do the same. It takes the location address as input and processes coordinates for that address.
要在地图上定位任何点,您需要具有其地理坐标( 纬度和经度 )。 地理编码是根据给定的位置地址计算这些地理坐标。 geocode()方法允许我们执行相同的操作。 它以位置地址作为输入并处理该地址的坐标。
address: Location address string
地址 :位置地址字符串
callback: Function called after geocoding
callback :地理编码后调用的函数
Let’s calculate the latitude and longitude for Stonehenge, located in United Kingdom. The snippet below will calculate the geographical coordinates of the given address, and center the map at that location. If no results are found, a message is displayed:
让我们计算英国的 巨石阵的经度和纬度。 下面的代码段将计算给定地址的地理坐标,并将地图定位在该位置。 如果未找到结果,则会显示一条消息:
GMaps.geocode({ address: 'Stonehenge, United Kingdom', callback: function(results, status) { if (status == 'OK') { latlng = results[0].geometry.location; mapObj.setCenter(latlng.lat(), latlng.lng()); } else if (status == 'ZERO_RESULTS') { alert('Sorry, no results found'); } } });setCenter() method takes latitude and longitude as its parameters and centers the map at that geographical location. It also accepts an optional callback parameter, a function triggered after the map is centered.
setCenter()方法将纬度和经度作为其参数,并将地图居中于该地理位置。 它还接受一个可选的回调参数,该参数在地图居中后触发。
There are two parameters in the callback function: results and status.
回调函数中有两个参数: results和status 。
results is an object array, storing the locations of all the places with the defined address. Since there can be more than one place with the same name, there can be more than one result. results stores each one of them. The location of the ith result can be determined using results[i].geometry.location.
results是一个对象数组,使用定义的地址存储所有位置的位置。 由于可以有多个具有相同名称的地方,因此可以有多个结果。 results存储其中的每一个。 第i 个结果的位置可以使用results[i].geometry.location 。
If no results were found for an address, status stores ZERO_RESULTS, else OK.
如果没有找到地址的结果,则status存储为ZERO_RESULTS ,否则为OK 。
Example Pen
示例笔
Geolocation calculates the user’s current geographical position. The geolocate() method lets us exploit this feature. It accepts an object literal with four properties, of which always is optional and the others all required. Each property is defined as a function that’s executed in specific cases:
地理位置计算用户的当前地理位置。 geolocate()方法使我们可以利用此功能。 它接受具有四个属性的对象文字,其中四个属性始终是可选的,而其他所有属性都是必需的。 每个属性都定义为在特定情况下执行的函数:
success: Geolocation was successful
成功 :地理定位成功
error: Geolocation was not successful
错误 :地理位置定位不成功
not_supported: Browser does not support geolocation
not_supported :浏览器不支持地理位置
always: Executed in every case
始终 :在每种情况下都执行
GMaps.geolocate({ success: function(position) { mapObj.setCenter(position.coords.latitude, position.coords.longitude); }, error: function(error) { alert('Geolocation failed: ' + error.message); }, not_supported: function() { alert("Your browser does not support geolocation"); }, always: function() { alert("Always"); } });Example Pen
示例笔
Polylines help to trace a path on a map. A path can be formed by joining coordinates of different points. The drawPolyline() method draws a polyline for a path. This path is provided as an array of coordinates (latitude and longitude). Apart from path, you can specify other properties for a polyline. Some of them are:
折线有助于在地图上跟踪路径。 可以通过合并不同点的坐标来形成路径。 drawPolyline()方法绘制路径的折线。 此路径以坐标数组( 纬度和经度 )的形式提供。 除了path之外,您还可以为折线指定其他属性。 他们之中有一些是:
strokeWeight
重量
strokeColor
strokeColor
strokeOpacity
strokeOpacity
All three define the style for the polyline. There are others as well, although we won’t be covering them in this article.
所有这三个定义折线的样式。 还有其他一些 ,尽管我们不会在本文中介绍它们。
var path = [ [-12.044012922866312, -77.02470665341184], [-12.05449279282314, -77.03024273281858], [-12.055122327623378, -77.03039293652341], [-12.075917129727586, -77.02764635449216], [-12.07635776902266, -77.02792530422971], [-12.076819390363665, -77.02893381481931], [-12.088527520066453, -77.0241058385925] ]; var pl = mapObj.drawPolyline({ path: path, strokeColor: '#76ff03', strokeOpacity: 1, strokeWeight: 10 });Example Pen
示例笔
A polyline can be removed using the removePolyline() method. It takes the polyline object as its parameter. Remove pl polyine using:
可以使用removePolyline()方法删除折线。 它以折线对象为参数。 使用以下方法除去pl多胺:
mapObj.removePolyline(pl);removePolylines() removes all the polylines associated with a map object.
removePolylines()删除与地图对象关联的所有折线。
mapObj.removePolylines();drawPolygon() helps you create a polygon on a map. Pretty much like the drawPolyline() method, you need to define a paths property. The stroke style properties (strokeWeight, strokeColor and strokeOpacity) work of polygon as well. They define the border of the polygon. Besides these, you can specify the fill color and opacity for the polygon:
drawPolygon()可帮助您在地图上创建多边形。 与drawPolyline()方法非常相似,您需要定义一个paths属性。 多边形的笔触样式属性( strokeWeight , strokeColor和strokeOpacity )也起作用。 它们定义了多边形的边界。 除此之外,您还可以指定多边形的填充颜色和不透明度:
fillColor
填色
fillOpacity
fillOpacity
Other polygon options can be found in the documentation.
其他多边形选项可在文档中找到。
var path = [ [-12.040397656836609, -77.03373871559225], [-12.040248585302038, -77.03993927003302], [-12.050047116528843, -77.02448169303511], [-12.044804866577001, -77.02154422636042] ]; var pg = mapObj.drawPolygon({ paths: path, strokeColor: '#000000', strokeOpacity: 0.3, strokeWeight: 2, fillColor: '#00e676', fillOpacity: 0.4 });Remember: It’s the path property for drawPolyline() and paths property for drawPolygon().
请记住:这是一个为path属性drawPolyline()和路径属性drawPolygon()
Example Pen
示例笔
To remove the polygon pg, use:
要删除多边形pg ,请使用:
mapObj.removePolygon(pg);Remove all polygons defined in mapObj:
删除mapObj定义的所有多边形:
mapObj.removePolygons();Creating circular shapes with drawPolygon() is not viable. drawCircle() helps you with that. Its parameter list includes:
用drawPolygon()创建圆形形状是不可行的。 drawCircle()可以帮助您。 其参数列表包括:
lat: Latitude for center
lat :中心的纬度
lng: Longitude for center
lng :中心经度
radius: Radius in meters on Earth’s surface.
radius :地球表面的半径,以米为单位。
Other options include styles for stroke and fill of shape (same as polygon), and some more.
其他选项包括笔触样式和形状填充(与多边形相同) 等 。
var c = mapObj.drawCircle({ lat: 51.178875, lng: -1.826259, radius: 300, fillColor: 'yellow', fillOpacity: 0.5, strokeWeight: 0, click: function(e){ alert('You are inside 300m radius of Stonehenge') } });Example Pen
示例笔
An overlay is a layer over the map with HTML content on it. GMaps supports overlays with the drawOverlay() method. It accepts the following hash:
叠加层是地图上具有HTML内容的图层。 GMaps使用drawOverlay()方法支持叠加层。 它接受以下哈希:
lat: Latitude
lat :纬度
lng: Longitude
lng :经度
content: HTML content
内容 :HTML内容
verticalAlign: top, middle, bottom
verticalAlign :顶部,中间,底部
horizontalAlgin: left, middle, right
horizontalAlgin :左,中,右
verticalOffset
verticalOffset
horizontalOffset
horizontalOffset
The alignments and offsets are with respect to the point defined by lat and lng.
对齐方式和偏移量相对于lat和lng定义的点。
Example snippet:
示例片段:
var ol = mapObj.drawOverlay({ lat: 27.1733151, lng: 78.0409684, content: '<div class="overlay">Taj Mahal</div>', verticalAlign: 'top', horizontalOffset: -40 });You can define CSS styles for the content. In our example, we have defined the overlay class.
您可以为内容定义CSS样式。 在我们的示例中,我们定义了overlay类。
.overlay { border: 1px solid #b71c1c; background: #d50000; padding: 5px; font-size: 17px; color: white; }Example Pen
示例笔
Remove overlay? Well, you know it:
删除覆盖物? 好吧,你知道的:
mapObj.removeOverlay(ol);Remove all overlays for a map object? You know that as well:
删除地图对象的所有叠加层? 您也知道:
mapObj.removeOverlays();A static map is an image of the map, which can independently be embedded into websites. GMaps lets you generate a URL to a static map. This URL can then be added as source to an image.
静态地图是地图的图像,可以独立地嵌入网站中。 GMaps允许您生成静态地图的URL。 然后可以将此URL作为源添加到图像。
staticMapURL() generates the required map URL after taking the following parameters:
采用以下参数后, staticMapURL()生成所需的地图URL:
size: An array of width and height in pixels
size :宽度和高度的数组,以像素为单位
lat
拉特
lng
ng
zoom
放大
Code snippet:
程式码片段:
url = GMaps.staticMapURL({ size: [500, 500], lat: 51.178882, lng: -1.8284037, zoom: 16 });Example Pen
示例笔
In our example, we have created an img element and added the URL to its src:
在我们的示例中,我们创建了一个img元素,并将URL添加到其src :
var map = document.getElementById('map'); var static_img = document.createElement('img'); static_img.src = url; map.appendChild(static_img);We can apply markers and polylines to static maps too.
我们也可以将标记和折线应用于静态地图。
Example Pen
示例笔
Mapit (view source on GitHub) creates a static map for a route between source and destination. Zoom down to an address on the map and place two markers (a source and a destination). Mapit will trace a route from one marker to another. It will create a url to the static map with the current configuration. You can preview the static map and download the image.
Mapit ( 在GitHub上查看源代码 )为源和目标之间的路由创建静态地图。 向下缩放至地图上的地址,然后放置两个标记(源和目的地)。 Mapit将跟踪从一个标记到另一个标记的路线。 它将使用当前配置创建指向静态地图的网址。 您可以预览静态地图并下载图像。
This article covers basic components of Maps. I’m sure it has served as a good getting-started guide to GMaps and interactive map applications. But it shouldn’t stop here. There is a lot more you can do with GMapsjs.
本文介绍了地图的基本组件。 我确信它已成为GMaps和交互式地图应用程序的入门指南。 但这不应该就此停止。 您可以使用GMapsjs做更多的事情 。
Have you used GMaps yet? If so, what has been your experience. If you have any comments or questions, please join the discussion below.
您使用过GMaps吗? 如果是这样,您的经验如何。 如果您有任何意见或疑问,请加入下面的讨论。
翻译自: https://www.sitepoint.com/google-maps-made-easy-with-gmaps-js/
gmaps.min.js
相关资源:gmaps_api_net