Created
March 21, 2019 17:36
-
-
Save klausbrunner/7ec4df179318cdad647014bc76c560c7 to your computer and use it in GitHub Desktop.
Trivial example to calculate route distances from a fixed point to location(s) specified as user input, using HERE Location Services.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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