Last active
March 19, 2024 20:01
-
-
Save TravelTime-Frontend/19ab8ad801609327cab65cc52d2a4ce3 to your computer and use it in GitHub Desktop.
Full code for how to use TravelTime data and draw Polygons and make intersections on Google maps
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
<html> | |
<head> | |
<style> | |
body { | |
background-color: gray; | |
} | |
html, | |
body, | |
#map { | |
height: 100%; | |
margin: 0; | |
padding: 0; | |
} | |
</style> | |
</head> | |
<body> | |
<div id='map'></div> | |
<script src='https://unpkg.com/@turf/turf/turf.min.js'></script> | |
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_GOES_HERE&callback=initMap" async defer></script> | |
<script> | |
var map; | |
function initMap() { | |
var mapOpts = { | |
center: { lat: 51.5031653, lng: -0.1123051 }, | |
zoom: 13, | |
}; | |
map = new google.maps.Map(document.getElementById('map'), mapOpts); | |
if (!google.maps.Polygon.prototype.getBounds) { | |
google.maps.Polygon.prototype.getBounds = function () { | |
var bounds = new google.maps.LatLngBounds(); | |
var paths = this.getPaths(); | |
var path; | |
for (var i = 0; i < paths.getLength(); i++) { | |
path = paths.getAt(i); | |
for (var ii = 0; ii < path.getLength(); ii++) { | |
bounds.extend(path.getAt(ii)); | |
} | |
} | |
return bounds; | |
} | |
} | |
sendGeocodingRequest(startingLocation, '#0000ff'); | |
sendGeocodingRequest(secondLocation, '#ff0000'); | |
} | |
// this function finds intersection between 2 shapes we've created | |
function intersection() { | |
// First, we map polygons to turf.polygon objects | |
// We use this turf library to easily find intersections between polygons, but you can always write your own one! | |
var poly1 = shapes[0].map(d => turf.polygon([d])); | |
var poly2 = shapes[1].map(d => turf.polygon([d])); | |
var intersections = []; | |
// Since we might have multi polygons, easiest way is to split it into polygons And find intersection between each of them | |
poly1.forEach(figure1 => poly2.forEach(figure2 => intersections.push(turf.intersect(figure1, figure2)))) | |
// Lets go through all intersections | |
intersections.forEach(poly => { | |
// Let's check if intersection exists. If there is no intersection it returns null | |
if (poly) { | |
var coordinates; | |
// coordinates object might contain single or multiple polygons, so we make it always to be as multiple polygons for easier code later. | |
if (poly.geometry.coordinates.length === 1) { | |
coordinates = [poly.geometry.coordinates] | |
} else { | |
coordinates = poly.geometry.coordinates | |
} | |
// Now we map all our polygons to google maps Polygon paths format { lat: x, lng: y } | |
var paths = coordinates.map(shape => shape.map(pol => pol.map(xy => { return { lat: xy[0], lng: xy[1] } }))) | |
// And lastly we draw our polygons on our map | |
paths.forEach(convertedPoly => { | |
var polygon = new google.maps.Polygon({ | |
paths: convertedPoly, | |
strokeColor: '#800080', | |
strokeOpacity: 1, | |
strokeWeight: 5, | |
fillColor: '#800080', | |
fillOpacity: 0.25 | |
}); | |
polygon.setMap(map); | |
}) | |
} | |
}) | |
} | |
// The name of the starting location. We will have to geocode this to coordinates. | |
var startingLocation = "London"; | |
var secondLocation = "London Royal Opera House"; | |
// The departure time in an ISO format. | |
var departureTime = new Date().toJSON(); | |
console.log(departureTime) | |
// Travel time in seconds. We want 30 minutes travel time so it is 30 minutes x 60 seconds. | |
var travelTime = 60 * 30; | |
// These secret variables are needed to authenticate the request. Get them from http://docs.traveltimeplatform.com/overview/getting-keys/ and replace | |
var APPLICATION_ID = "PLACE YOUR ID HERE"; | |
var API_KEY = "PLACE YOUR KEY HERE"; | |
var ids = ['first_location', 'second_location', 'third_location'] | |
var shapes = []; | |
// Sends the geocoding request. | |
function sendGeocodingRequest(location, color) { | |
// The request for the geocoder. Reference: http://docs.traveltimeplatform.com/reference/geocoding-search/ | |
var request = { | |
query: location | |
}; | |
var xhr = new XMLHttpRequest(); | |
xhr.responseType = "json"; | |
xhr.open("GET", "https://api.traveltimeapp.com/v4/geocoding/search?query=" + location) | |
xhr.setRequestHeader("X-Application-Id", APPLICATION_ID); | |
xhr.setRequestHeader("X-Api-Key", API_KEY); | |
xhr.setRequestHeader("Accept-Language", " en-US"); | |
xhr.onreadystatechange = function () { | |
if (xhr.status >= 200 && xhr.status < 300) { | |
if (xhr.readyState === 4) { | |
return sendTimeMapRequest(xhr.response, location, color) | |
} | |
} else { | |
console.error("Wrong response, check your login") | |
} | |
}; | |
xhr.send(); | |
}; | |
// Sends the request of the Time Map multipolygon. | |
function sendTimeMapRequest(geocodingResponse, location, color) { | |
// The request for Time Map. Reference: http://docs.traveltimeplatform.com/reference/time-map/ | |
var coords = geocodingResponse.features[0].geometry.coordinates; | |
var latLng = { lat: coords[1], lng: coords[0] }; | |
var request = { | |
departure_searches: [{ | |
id: "first_location", | |
coords: latLng, | |
transportation: { type: "public_transport" }, | |
departure_time: departureTime, | |
travel_time: travelTime | |
}], | |
arrival_searches: [] | |
}; | |
var xhr = new XMLHttpRequest() | |
xhr.addEventListener("readystatechange", function () { | |
if (this.readyState === 4) { | |
return drawTimeMap(this.response); | |
} | |
}); | |
xhr.open("POST", "https://api.traveltimeapp.com/v4/time-map") | |
xhr.setRequestHeader("X-Application-Id", APPLICATION_ID); | |
xhr.setRequestHeader("X-Api-Key", API_KEY); | |
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8"); | |
xhr.responseType = "json"; | |
xhr.send(JSON.stringify(request)); | |
// Draws the resulting multipolygon from the response on the map. | |
function drawTimeMap(response) { | |
// Reference for the response: http://docs.traveltimeplatform.com/reference/time-map/#response-body-json-attributes | |
var paths = response.results[0].shapes.map(function (polygon) { | |
var shell = polygon.shell | |
var holes = polygon.holes | |
return [shell].concat(holes); | |
}).map(x => x[0]); | |
// Let's map coordinates to array in [ lat, lng ] format and store them | |
shapes.push(paths.map(pol => pol.map(latlng => [latlng.lat, latlng.lng]))) | |
var polygon = new google.maps.Polygon({ | |
paths, | |
strokeColor: color, | |
strokeOpacity: 1, | |
strokeWeight: 5, | |
fillColor: color, | |
fillOpacity: 0.25 | |
}); | |
polygon.setMap(map); | |
map.fitBounds(polygon.getBounds()) | |
// After 2nd shape is added we call intersection function | |
if (shapes.length === 2) intersection(); | |
}; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment