Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Trivial example to calculate route distances from a fixed point to location(s) specified as user input, using HERE Location Services.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="http://js.api.here.com/v3/3.0/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
<script src="http://js.api.here.com/v3/3.0/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<form onsubmit="geocodeAndRoute(); return false">
<input type="text" id="address"><input type="submit">
</form>
<table>
<thead>
<tr>
<th>Location</th>
<th>Distance to drive</th>
</tr>
</thead>
<tbody id="resultsTable"></tbody>
</table>
<script>
const sourceLocation = '52.5214,13.41555'
const platform = new H.service.Platform({
'app_id': 'YOUR_APP_ID_GOES_HERE',
'app_code': 'YOUR_APP_CODE_GOES_HERE'
})
const geocoder = platform.getGeocodingService()
const router = platform.getRoutingService()
const onGeocodeResult = (result) => {
const table = document.getElementById('resultsTable')
table.innerHTML = ''
if (result.Response.View.length) {
const locations = result.Response.View[0].Result
for (loc of locations) {
const row = table.insertRow(-1)
row.insertCell(-1).innerHTML = loc.Location.Address.Label
const { Latitude, Longitude } = loc.Location.DisplayPosition
const routeCell = row.insertCell(-1)
const routingParameters = {
'mode': 'fastest;car;traffic:disabled',
'waypoint0': 'geo!' + sourceLocation,
'waypoint1': 'geo!' + Latitude + ',' + Longitude,
'representation': 'overview'
}
// calculate each route separately (alternatively, could use the Matrix Routing API)
router.calculateRoute(routingParameters, routeResult => {
if (routeResult.response) {
const distKm = routeResult.response.route[0].summary.distance / 1000
routeCell.innerHTML = distKm
} else { // no route found
routeCell.innerHTML = 'unknown'
}
}, (error) => alert(error.message))
}
} else {
// no matching location found
}
}
function geocodeAndRoute() {
const address = document.getElementById('address').value
const geoparams = { searchText: address }
geocoder.geocode(geoparams, onGeocodeResult, (error) => alert(error.message))
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.