This package comes with a number of classes:
Gmap
- base class that can be used to render a map and place markers on itService
- Abstract class used to extend service classes fromObservable
- Event registration and dispatching classDirections
- Service instance with which routes can be calculated and plotted on the map
The Gmap class can tap into all Google Maps APIs. The available APIs are listed here: https://developers.google.com/maps/documentation/javascript/reference/3.exp/.
import { Gmap } from 'gmap-base';
// reference the element in which the map should be rendered
const rootElement = document.getElementById('map-container)';
// set the center; a regular address is expected and will be geocoded by the class
const center = 'Dam Square, Amsterdam';
// set the value for the API key. Note that the key should be set to have access to, at least, the Maps Javascript API as well as the Directions API (or Maps and Routes in the Google Maps Platform settings)
const apiKey = 'here-be-a-google-api-key';
// instantiate the map class. By default, the map is rendered in the root element, unless 'renderMapOnApiReady' is passed to the constructor with value 'false'.
const gmap = new Gmap({
rootElement,
center,
apiKey,
// any valid MapOptions interface option can be passed in here
// see https://developers.google.com/maps/documentation/javascript/reference/3.exp/map#MapOptions for reference
options = { ... },
});
let gmap;
// define callbacks. Not required if no interacting is needed
const onMapReady = () => {
// the map is instantiated and has been rendered in the root element; markers can be placed or other interactions can take place
gmap.addMarker('Baarn, Paleis Soestdijk, Baarn', (marker) => {
// adding markers is asynchronous, use a callback function to ensure that the marker has been added to the map before interacting with it
});
gmap.addMarker('Keukenhof, Stationsweg, Lisse');
// etc. etc.
// after setting markers, the bounds are not automatically updated. Calling 'fitBoundsToVisibleMarkers' will take care of that
gmap.fitBoundsToVisibleMarkers();
// removing a marker
gmap.removeMarker('Baarn, Paleis Soestdijk, Baarn');
};
// instantiate the map class
gmap = new Gmap({
rootElement,
center,
apiKey,
callbacks: {
MAP_READY: onMapReady,
},
});
A callback function can be assigned to the following events:
API_READY
- inidicates that Google Maps APIs can be instantiated.MAP_READY
- the Gmap class instantiated successfully and the map is rendered, centered on the location of the address.UNKNOWN_ERROR
- indicates that the request could not be processed due to a server error. The request may succeed if you try again.OVER_QUERY_LIMIT
- indicates that you are over your quota.REQUEST_DENIED
- indicates that your request was denied.INVALID_REQUEST
- generally indicates that the query (address, components or latlng) is missing.ZERO_RESULTS
- indicates that the geocode was successful but returned no results. This may occur if the geocoder was passed a non-existent address.ERROR
- indicates that the request timed out or there was a problem contacting the Google servers. The request may succeed if you try again.
The Gmap class offers the following methods to interact with the map:
activateInfoWindow(infoWindow, InfoWindowOptions)
- Show an infoWindow at the given positionaddInfoWindow(google.maps.InfoWindow)
- Push an InfoWindow object onto the stackaddMarker(address)
- Add a marker for a specific address to the mapcloseInfoWindows
- Close all InfoWindow instances that have be registeredfitBoundsToVisibleMarkers
- Resize and recenter the core map instance taken the bounds of all visible markersrenderMap
- Render an instance of the map in the given rootElementremoveMarker(marker)
- Remove a marker from the map by unsetting its reference to the Core map instancesetCenter(address)
- Center the map on a given addressunsetMarkers
- Remove all markers from the map
The Google Maps API comes with a number of services that can be used in conjunction with a rendered map. This gmap-base
package offer one service: Directions
.
This service can render routes and provide alternatives for those routes and plot them on the map. The service can receive a location (in the form of an address) as well as a travel mode. Valid travel modes:
TRANSIT
WALKING
BICYCLING
DRIVING
import { Gmap, DirectionsService } from 'gmap-base';
let gmap;
// define callback functions
const onApiReady = () => {
// the Google Maps Directions API is not ready before this callback function is called
// create a new class instance
const directionsService = new DirectionsService({
callbacks: {
NOT_FOUND: (response) => {
// handle an unfound location
},
OK: (response) => {
// origin address has been found
},
},
});
// and add it to the map instance
gmap.addService(directionsService);
};
// instantiate the map class
gmap = new Gmap({
rootElement,
center,
apiKey,
callbacks: {
API_READY: onApiReady,
},
});
Assuming that the page in which the map is rendered, has a form with fields that allow for entering an address as well as selecting a travel mode, your implementation should have a function that handles that type of input:
const onChangeDirections = (destination, origin, travelMode) => {
const directionsService = gmap.getService('Directions');
directionsService
.setInfoWindowContentFunc(this.infoWindowContent)
.showRoutes({
destination,
origin,
travelMode,
provideRouteAlternatives: true,
});
}
Calling showRoutes
will render the results of the directions request on the map. If provideRouteAlternatives
was passed in, the result will render all suggestions on the map. Each route is clickable and will show a infoWindow when clicked. In order to customise the infowindow contents, a function can be assigned through setInfoWindowContentFunc
:
const infoWindowContent = ({ travelMode, distance, duration }) => `
${travelMode}<br />
Distance: ${distance}<br />
Duration: ${duration}
`;
The function takes an options object as its parameter with the keys travelMode
, distance
and duration
.
The Directions class offers the following methods to interact with the map:
activateRoute(route)
- Display a route with the active stroke coloraddRoute(route)
- Push a Route object onto the stackdeactivateRoutes
- Display routes with the idle stroke colorfitBoundsToRoutes
- Calling this will re-center the map with all routes in the viewportgetRoutes(options, callback)
- Get all route and possible suggestions from the DirectionsServicesetInfoWindowContentFunc(infoWindowContentFunc)
- Set the InfoWindow content generation functionremoveOriginMarker
- Remove the origin marker from the core map instanceresetDirections
- Clear the core map instance, removing all routes and, when the origin has changed, removing the origin markersetDefaults(options)
- Set route propertiessetOrigin(address)
- Set the origin for the routesshowOriginMarker
- Place a marker on the map to indicate the origin for the routesshowRoutes
- Render routes directly on the core map instance