Home >Technology peripherals >It Industry >Google Maps Made Easy with GMaps.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 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.
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.
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.
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:
<span>var map; </span><span>function initMap() { </span> map <span>= new google<span>.maps.Map</span>(document.getElementById('map'), { </span> <span>center: {lat: -34.397, lng: 150.644}, </span> <span>zoom: 8 </span> <span>}); </span><span>}</span>
map is the HTML element id where the map will load.
We can write the same basic app with GMaps like this:
<span>var map; </span><span>function initMap() { </span> map <span>= new google<span>.maps.Map</span>(document.getElementById('map'), { </span> <span>center: {lat: -34.397, lng: 150.644}, </span> <span>zoom: 8 </span> <span>}); </span><span>}</span>
This tutorial will guide you through some of the most used components in maps, with example Pens to demonstrate each.
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.
<span>new GMaps({ </span> <span>el: '#map', </span> <span>lat: -34.397, </span> <span>lng: 150.644, </span> <span>zoom: 8 </span><span>});</span>
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.
The Maps API offers various components for customizing maps. The same components can be added with GMaps with less code.
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:
<span><span><!doctype html></span> </span><span><span><span><html</span>></span> </span> <span><span><span><head</span>></span> </span> <span><span><span><style</span>></span><span> </span></span><span><span> <span><span>#map</span> { </span></span></span><span><span> <span>width: 400px; </span></span></span><span><span> <span>height: 400px; </span></span></span><span><span> <span>} </span></span></span><span><span> </span><span><span></style</span>></span> </span> <span><span><span></head</span>></span> </span> <span><span><span><body</span>></span> </span> <span><span><span><div</span> id<span>="map"</span>></span><span><span></div</span>></span> </span> <span><!-- Google Maps JS API --> </span> <span><span><span><script</span> src<span>="https://maps.googleapis.com/maps/api/js"</span>></span><span><span></script</span>></span> </span> <span><!-- GMaps Library --> </span> <span><span><span><script</span> src<span>="gmaps.js"</span>></span><span><span></script</span>></span> </span> <span><span><span><script</span>></span><span> </span></span><span><span> <span>/* Map Object */ </span></span></span><span><span> <span>var mapObj = new GMaps({ </span></span></span><span><span> <span>el: '#map', </span></span></span><span><span> <span>lat: 48.857, </span></span></span><span><span> <span>lng: 2.295 </span></span></span><span><span> <span>}); </span></span></span><span><span> </span><span><span></script</span>></span> </span> <span><span><span></body</span>></span> </span><span><span><span></html</span>></span></span>
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:
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:
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:
infoWindow supports some more options.
This snippet is a valid example of addMarker():
<span>var mapObj = new GMaps({ </span> <span>el: '#map', </span> <span>lat: 48.857, </span> <span>lng: 2.295, </span> <span>click: function(e) { </span> <span>alert('You clicked on the map'); </span> <span>}, </span> <span>zoom_changed: function(e) { </span> <span>alert('You zoomed the map'); </span> <span>} </span><span>});</span>
addMarker() also accepts events – for example, a marker reacting to mouseover event:
<span>var m = mapObj.addMarker({ </span> <span>lat: 48.8583701, </span> <span>lng: 2.2944813, </span> <span>title: 'Eiffel Tower', </span> <span>infoWindow: { </span> <span>content: '<h4>Eiffel Tower</h4><div>Paris, France</div>', </span> <span>maxWidth: 100 </span> <span>} </span><span>});</span>
Example Pen
A marker can be removed using the removeMarker() method. Pass the marker object to it (m in our case) as an argument:
mapObj<span>.addMarker({ </span> <span>lat: 48.8583701, </span> <span>lng: 2.2944813, </span> <span>mouseover: function(e) { </span> <span>alert('Triggered'); </span> <span>} </span><span>});</span>
removeMarkers() collectively removes all the markers associated with the map object.
<span>var map; </span><span>function initMap() { </span> map <span>= new google<span>.maps.Map</span>(document.getElementById('map'), { </span> <span>center: {lat: -34.397, lng: 150.644}, </span> <span>zoom: 8 </span> <span>}); </span><span>}</span>
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.
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:
<span>new GMaps({ </span> <span>el: '#map', </span> <span>lat: -34.397, </span> <span>lng: 150.644, </span> <span>zoom: 8 </span><span>});</span>
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.
There are two parameters in the callback function: results and 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.
If no results were found for an address, status stores ZERO_RESULTS
, else 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:
<span><span><!doctype html></span> </span><span><span><span><html</span>></span> </span> <span><span><span><head</span>></span> </span> <span><span><span><style</span>></span><span> </span></span><span><span> <span><span>#map</span> { </span></span></span><span><span> <span>width: 400px; </span></span></span><span><span> <span>height: 400px; </span></span></span><span><span> <span>} </span></span></span><span><span> </span><span><span></style</span>></span> </span> <span><span><span></head</span>></span> </span> <span><span><span><body</span>></span> </span> <span><span><span><div</span> id<span>="map"</span>></span><span><span></div</span>></span> </span> <span><!-- Google Maps JS API --> </span> <span><span><span><script</span> src<span>="https://maps.googleapis.com/maps/api/js"</span>></span><span><span></script</span>></span> </span> <span><!-- GMaps Library --> </span> <span><span><span><script</span> src<span>="gmaps.js"</span>></span><span><span></script</span>></span> </span> <span><span><span><script</span>></span><span> </span></span><span><span> <span>/* Map Object */ </span></span></span><span><span> <span>var mapObj = new GMaps({ </span></span></span><span><span> <span>el: '#map', </span></span></span><span><span> <span>lat: 48.857, </span></span></span><span><span> <span>lng: 2.295 </span></span></span><span><span> <span>}); </span></span></span><span><span> </span><span><span></script</span>></span> </span> <span><span><span></body</span>></span> </span><span><span><span></html</span>></span></span>
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:
All three define the style for the polyline. There are others as well, although we won’t be covering them in this article.
<span>var mapObj = new GMaps({ </span> <span>el: '#map', </span> <span>lat: 48.857, </span> <span>lng: 2.295, </span> <span>click: function(e) { </span> <span>alert('You clicked on the map'); </span> <span>}, </span> <span>zoom_changed: function(e) { </span> <span>alert('You zoomed the map'); </span> <span>} </span><span>});</span>
Example Pen
A polyline can be removed using the removePolyline() method. It takes the polyline object as its parameter. Remove pl polyine using:
<span>var map; </span><span>function initMap() { </span> map <span>= new google<span>.maps.Map</span>(document.getElementById('map'), { </span> <span>center: {lat: -34.397, lng: 150.644}, </span> <span>zoom: 8 </span> <span>}); </span><span>}</span>
removePolylines() removes all the polylines associated with a map object.
<span>new GMaps({ </span> <span>el: '#map', </span> <span>lat: -34.397, </span> <span>lng: 150.644, </span> <span>zoom: 8 </span><span>});</span>
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:
Other polygon options can be found in the documentation.
<span><span><!doctype html></span> </span><span><span><span><html</span>></span> </span> <span><span><span><head</span>></span> </span> <span><span><span><style</span>></span><span> </span></span><span><span> <span><span>#map</span> { </span></span></span><span><span> <span>width: 400px; </span></span></span><span><span> <span>height: 400px; </span></span></span><span><span> <span>} </span></span></span><span><span> </span><span><span></style</span>></span> </span> <span><span><span></head</span>></span> </span> <span><span><span><body</span>></span> </span> <span><span><span><div</span> id<span>="map"</span>></span><span><span></div</span>></span> </span> <span><!-- Google Maps JS API --> </span> <span><span><span><script</span> src<span>="https://maps.googleapis.com/maps/api/js"</span>></span><span><span></script</span>></span> </span> <span><!-- GMaps Library --> </span> <span><span><span><script</span> src<span>="gmaps.js"</span>></span><span><span></script</span>></span> </span> <span><span><span><script</span>></span><span> </span></span><span><span> <span>/* Map Object */ </span></span></span><span><span> <span>var mapObj = new GMaps({ </span></span></span><span><span> <span>el: '#map', </span></span></span><span><span> <span>lat: 48.857, </span></span></span><span><span> <span>lng: 2.295 </span></span></span><span><span> <span>}); </span></span></span><span><span> </span><span><span></script</span>></span> </span> <span><span><span></body</span>></span> </span><span><span><span></html</span>></span></span>
Remember: It’s the path property for drawPolyline() and paths property for drawPolygon().
Example Pen
To remove the polygon pg, use:
<span>var mapObj = new GMaps({ </span> <span>el: '#map', </span> <span>lat: 48.857, </span> <span>lng: 2.295, </span> <span>click: function(e) { </span> <span>alert('You clicked on the map'); </span> <span>}, </span> <span>zoom_changed: function(e) { </span> <span>alert('You zoomed the map'); </span> <span>} </span><span>});</span>
Remove all polygons defined in mapObj:
<span>var m = mapObj.addMarker({ </span> <span>lat: 48.8583701, </span> <span>lng: 2.2944813, </span> <span>title: 'Eiffel Tower', </span> <span>infoWindow: { </span> <span>content: '<h4>Eiffel Tower</h4><div>Paris, France</div>', </span> <span>maxWidth: 100 </span> <span>} </span><span>});</span>
Creating circular shapes with drawPolygon() is not viable. drawCircle() helps you with that. Its parameter list includes:
Other options include styles for stroke and fill of shape (same as polygon), and some more.
mapObj<span>.addMarker({ </span> <span>lat: 48.8583701, </span> <span>lng: 2.2944813, </span> <span>mouseover: function(e) { </span> <span>alert('Triggered'); </span> <span>} </span><span>});</span>
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:
The alignments and offsets are with respect to the point defined by lat and lng.
Example snippet:
mapObj<span>.removeMarker(m);</span>
You can define CSS styles for the content. In our example, we have defined the overlay class.
mapObj<span>.removeMarkers();</span>
Example Pen
Remove overlay? Well, you know it:
<span>GMaps.geocode({ </span> <span>address: 'Stonehenge, United Kingdom', </span> <span>callback: function(results<span>, status</span>) { </span> <span>if (status == 'OK') { </span> latlng <span>= results[0].geometry.location; </span> mapObj<span>.setCenter(latlng.lat(), latlng.lng()); </span> <span>} else if (status == 'ZERO_RESULTS') { </span> <span>alert('Sorry, no results found'); </span> <span>} </span> <span>} </span><span>});</span>
Remove all overlays for a map object? You know that as well:
<span>GMaps.geolocate({ </span> <span>success: function(position) { </span> mapObj<span>.setCenter(position.coords.latitude, position.coords.longitude); </span> <span>}, </span> <span>error: function(error) { </span> <span>alert('Geolocation failed: ' + error.message); </span> <span>}, </span> <span>not_supported: function() { </span> <span>alert("Your browser does not support geolocation"); </span> <span>}, </span> <span>always: function() { </span> <span>alert("Always"); </span> <span>} </span><span>});</span>
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.
staticMapURL() generates the required map URL after taking the following parameters:
Code snippet:
<span>var path = [ </span> <span>[-12.044012922866312, -77.02470665341184], </span> <span>[-12.05449279282314, -77.03024273281858], </span> <span>[-12.055122327623378, -77.03039293652341], </span> <span>[-12.075917129727586, -77.02764635449216], </span> <span>[-12.07635776902266, -77.02792530422971], </span> <span>[-12.076819390363665, -77.02893381481931], </span> <span>[-12.088527520066453, -77.0241058385925] </span><span>]; </span> <span>var pl = mapObj.drawPolyline({ </span> <span>path: path, </span> <span>strokeColor: '#76ff03', </span> <span>strokeOpacity: 1, </span> <span>strokeWeight: 10 </span><span>});</span>
Example Pen
In our example, we have created an img element and added the URL to its src:
mapObj<span>.removePolyline(pl);</span>
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.
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.
Have you used GMaps yet? If so, what has been your experience. If you have any comments or questions, please join the discussion below.
To get started with Gmaps.js, you first need to include the Google Maps JavaScript API in your HTML file. After that, include the Gmaps.js library. You can download it from the official GitHub repository or use a CDN. Once you’ve included these scripts, you can initialize a new map by creating a new GMaps object and passing in the id of the HTML element where you want the map to be displayed, along with some options like the latitude and longitude of the center of the map.
Gmaps.js simplifies the process of working with Google Maps. It provides a simple and intuitive API for creating and manipulating maps. Key features include the ability to easily add markers, polygons, and layers, geolocation, geocoding, and more. It also supports events, allowing you to respond to user interactions such as clicks or drags.
Adding markers to a map with Gmaps.js is straightforward. You can use the addMarker method on your GMaps object, passing in an object with the latitude and longitude of the marker. You can also include other options like the title, click events, and more.
Gmaps.js provides a getGeolocation method that you can use to get the user’s current location. This method returns a promise that resolves with the user’s latitude and longitude. You can then use this information to center the map on the user’s location or add a marker at their location.
Geocoding is the process of converting addresses into geographic coordinates, which you can use to place markers or position the map. Gmaps.js provides a geocode method that takes an address and returns a promise that resolves with the geocoded result.
Gmaps.js supports a variety of events, including click, drag, zoom_changed, and more. You can add an event listener to your GMaps object using the addListener method, passing in the event name and a callback function to be executed when the event occurs.
Gmaps.js supports adding various types of layers to a map, including traffic, transit, and bicycle layers. You can add a layer using the addLayer method on your GMaps object, passing in the name of the layer.
Gmaps.js provides methods for drawing various shapes on a map, including lines, polygons, circles, and rectangles. You can use the drawOverlay, drawPolygon, drawCircle, and drawRectangle methods on your GMaps object.
Gmaps.js allows you to customize the appearance of a map using styles. You can pass in a styles option when creating your GMaps object, which should be an array of style objects that describe how different elements of the map should be styled.
Gmaps.js provides a way to handle errors that occur when using the library. You can listen for the ‘error’ event on your GMaps object, which will be triggered whenever an error occurs. The event object will contain information about the error, including a message and a stack trace.
The above is the detailed content of Google Maps Made Easy with GMaps.js. For more information, please follow other related articles on the PHP Chinese website!