How to make the polyline change with the draggable route [duplicate] - google-maps

This question already has answers here:
How to get a draggable waypoint's location from google directions result
(1 answer)
Google Maps API v3 - Directions with draggable alternate routes
(1 answer)
suppressMarkers and draggable for DirectionsRendererOptions Google Maps API
(1 answer)
How do I change the route provided to me by the directions API on web?
(1 answer)
Closed last month.
I am trying to create a polyline from the route. The route is draggable and it has waypoints. I am using the directions_changed event listener to draw the polyline so that whenever the route changes the polyline also changes. I am able to achieve all of this except then when I drag the route I get the new polyline but I also have the older polyline drawn on the route. Whenever the route is dragged I don't want the older polyline to appear along with the new polyline.
How can I achieve this?
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 4,
center: { lat: -24.345, lng: 134.46 }, // Australia.
});
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer({
draggable: true,
map,
panel: document.getElementById("panel"),
});
directionsRenderer.addListener("directions_changed", () => {
const directions = directionsRenderer.getDirections();
if (directions) {
computeTotalDistance(directions);
var polyline = new google.maps.Polyline(
{
path:google.maps.geometry.encoding.decodePath(directions.routes[0].overview_polyline),
map : map
}
)
if(polyline)
{
console.log(polyline)
polyline.setMap(map)
}
}
});
displayRoute(
"Perth, WA",
"Sydney, NSW",
directionsService,
directionsRenderer
);
}
function displayRoute(origin, destination, service, display) {
service
.route({
origin: origin,
destination: destination,
waypoints: [
{ location: "Adelaide, SA" },
{ location: "Broken Hill, NSW" },
],
travelMode: google.maps.TravelMode.DRIVING,
avoidTolls: true,
})
.then((result) => {
display.setDirections(result);
})
.catch((e) => {
alert("Could not display directions due to: " + e);
});
}
function computeTotalDistance(result) {
let total = 0;
const myroute = result.routes[0];
if (!myroute) {
return;
}
for (let i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000;
document.getElementById("total").innerHTML = total + " km";
}
window.initMap = initMap;

If you want to hide the old polyline, keep a reference to it (outside the scope of the directions_changed listener) and remove it from the map with polyline.setMap(null); before creating the new polyline:
if (polyline) {
// if polyline already exists, remove it from the map.
polyline.setMap(null)
}
polyline = new google.maps.Polyline({
path: google.maps.geometry.encoding.decodePath(directions.routes[0].overview_polyline),
map: map
})
proof of concept fiddle
code snippet:
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 4,
center: {
lat: -24.345,
lng: 134.46
}, // Australia.
});
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer({
draggable: true,
map,
panel: document.getElementById("panel"),
});
let polyline;
directionsRenderer.addListener("directions_changed", () => {
const directions = directionsRenderer.getDirections();
if (directions) {
computeTotalDistance(directions);
if (polyline) {
// if polyline already exists, remove it from the map.
polyline.setMap(null)
}
polyline = new google.maps.Polyline({
path: google.maps.geometry.encoding.decodePath(directions.routes[0].overview_polyline),
map: map
})
if (polyline) {
console.log(polyline)
polyline.setMap(map)
}
}
});
displayRoute(
"Perth, WA",
"Sydney, NSW",
directionsService,
directionsRenderer
);
}
function displayRoute(origin, destination, service, display) {
service
.route({
origin: origin,
destination: destination,
waypoints: [{
location: "Adelaide, SA"
},
{
location: "Broken Hill, NSW"
},
],
travelMode: google.maps.TravelMode.DRIVING,
avoidTolls: true,
})
.then((result) => {
display.setDirections(result);
})
.catch((e) => {
alert("Could not display directions due to: " + e);
});
}
function computeTotalDistance(result) {
let total = 0;
const myroute = result.routes[0];
if (!myroute) {
return;
}
for (let i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000;
document.getElementById("total").innerHTML = total + " km";
}
window.initMap = initMap;
/*
* Always set the map height explicitly to define the size of the div element
* that contains the map.
*/
#map {
height: 90%;
}
/*
* Optional: Makes the sample page fill the window.
*/
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: "Roboto", "sans-serif";
line-height: 30px;
padding-left: 10px;
}
<!DOCTYPE html>
<html>
<head>
<title>Directions Service</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="total"></div>
<div id="map"></div>
<!--
The `defer` attribute causes the callback to execute after the full HTML
document has been parsed. For non-blocking uses, avoiding race conditions,
and consistent behavior across browsers, consider loading using Promises
with https://www.npmjs.com/package/#googlemaps/js-api-loader.
-->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly" defer></script>
</body>
</html>

Related

Google Maps MarkerClusterer not showing any default images

I'm adding javascript code snippet to my Wordpress post (Hosted by a 3rd Party). I managed to create an array of Markers, and had them added to the MarkerClusterer and Map. The cluster shows up but as a broken image link and a number.
How do I access the MarkerClusterer default images? I followed the instructions from https://github.com/googlemaps/js-markerclusterer/blob/main/README.md
I'm not sure how to use npm with the 3rd party hosting. I don't use a database with my website. I'm calling src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js" to import MarkerClusterer
<div id="gmap" style="width:100%;height:400px;"></div>
<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"</script>
var mymap;
var markers = [];
function initMap() {
var centerpoint = { lat: 38.5, lng: -98 }; //centered around Kansas
mymap = new google.maps.Map(document.getElementById('gmap'), {
zoom: 4,
center: centerpoint
});
}
/** fetching a cvs file on the server side with a list of locations */
fetch("https://mywebsite.com/wp-content/uploads/2022/03/stores.csv")
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.text().then(function(data) {
count = 0;
console.log("fetch called successfully");
initMap();
processCSV(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
function processCSV(allData){
const rows = allData.split('\n');
var storename, storephone, storeaddress, storelat, storelng;
for(let i=0; i<rows.length; i++){
var line = rows[i];
storename = line.split(",")[1];
storephone = line.split(",")[3];
storeaddress = String(line.split(",")[2]);
storeaddress = replaceAll(storeaddress, "^", ",");
storelat = line.split(",")[4];
storelng = line.split(",")[5];
createMarker(storename, storephone, storeaddress, storelat, storelng);
}
createCluster();
}
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
function createCluster(){
var mcluster =new MarkerClusterer( mymap , markers);
}
function createMarker(name, phone, address, latstr, lngstr) {
var contentString = "<b>" + name + "</b><br><br><i>" + phone + "</i><br><br>" + address;
var latLng = { lat: Number(latstr) , lng: Number(lngstr)};
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
var marker = new google.maps.Marker({
position: latLng,
map: mymap,
title: name
});
markers.push(marker);
console.log("added marker to map" + name);
marker.addListener("click", () => {
infowindow.open({
anchor: marker,
map: mymap,
shouldFocus: false,
});
});
}
<script src="https://maps.googleapis.com/maps/api/js?key=<PRIVATEKEY>;callback=initMap"></script>
The version of MarkerClusterer you are using doesn't require ClusterIcons (unless you want to change them), they default to SVG icons coded inline.
When I run the posted code I get a javascript error: Uncaught (in promise) ReferenceError: MarkerClusterer is not defined.
That is because according to the documentation when you include the library the way you are (<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"></script>), the constructor for the MarkerClusterer is accessed as:
When adding via unpkg, the MarkerClusterer can be accessed at markerClusterer.MarkerClusterer.
Changing that, makes the clusters appear.
proof of concept fiddle
code snippet:
var mymap;
var markers = [];
function initMap() {
var centerpoint = {
lat: 40.7127753,
lng: -74.0059728
}; //centered around New York City
mymap = new google.maps.Map(document.getElementById('gmap'), {
zoom: 4,
center: centerpoint
});
processCSV(data);
}
var data = '"","New York","New York^ NY","516-555-5555",40.7127753, -74.0059728\n"","Newark","Newark^ NJ","201-555-5555",40.735657, -74.1723667';
function processCSV(allData) {
console.log(allData);
const rows = allData.split('\n');
var storename, storephone, storeaddress, storelat, storelng;
for (let i = 0; i < rows.length; i++) {
var line = rows[i];
storename = line.split(",")[1];
storephone = line.split(",")[3];
storeaddress = String(line.split(",")[2]);
storeaddress = replaceAll(storeaddress, "^", ",");
storelat = line.split(",")[4];
storelng = line.split(",")[5];
createMarker(storename, storephone, storeaddress, storelat, storelng);
}
createCluster();
}
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
function createCluster() {
var mcluster = new markerClusterer.MarkerClusterer({
map: mymap,
markers: markers
});
}
function createMarker(name, phone, address, latstr, lngstr) {
var contentString = "<b>" + name + "</b><br><br><i>" + phone + "</i><br><br>" + address;
var latLng = {
lat: Number(latstr),
lng: Number(lngstr)
};
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
var marker = new google.maps.Marker({
position: latLng,
map: mymap,
title: name
});
markers.push(marker);
console.log("added marker to map" + name);
marker.addListener("click", () => {
infowindow.open({
anchor: marker,
map: mymap,
shouldFocus: false,
});
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#gmap {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="gmap"></div>
<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"></script>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
</body>
</html>

Convert address into coordinates for Google Maps Local Context (Geocoding + Local Context Maps)

I am attempting to plug Google Maps Local Context into my website, and I am looking to use an address string (1234 Main St, City, State, USA) to center and display a marker on my map.
Here's the code I have that displays a simple map on the site, but I need help getting an address to work instead of coordinates.
I have to use Geocoder, but I need help tying it together with the Google Maps Local Context map.
let map;
function initMap() {
const localContextMapView = new google.maps.localContext.LocalContextMapView({
element: document.getElementById("map"),
placeTypePreferences: ["restaurant", "tourist_attraction"],
maxPlaceCount: 12,
});
const center = { lat: 37.4219998, lng: -122.0840572 };
map = localContextMapView.map;
new google.maps.Marker({ position: center, map: map });
map.setOptions({
center: center,
zoom: 14,
});
}
https://jsfiddle.net/cegytdj6/
code snippet:*
let map;
function initMap() {
const localContextMapView = new google.maps.localContext.LocalContextMapView({
element: document.getElementById("map"),
placeTypePreferences: ["restaurant", "tourist_attraction"],
maxPlaceCount: 12,
});
const center = {
lat: 37.4219998,
lng: -122.0840572
};
map = localContextMapView.map;
new google.maps.Marker({
position: center,
map: map
});
map.setOptions({
center: center,
zoom: 14,
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Local Context Basic</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=localContext&v=beta" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
</body>
</html>
See the simple geocoder example for how to use the geocoder in the Google Maps Javascript API v3.
The code below will use the geocoder to return the coordinates for "1600 Amphitheatre Parkway, Mountain View, CA".
let geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: "1600 Amphitheatre Parkway, Mountain View, CA" }, (results, status) => {
if (status === "OK") {
const center = results[0].geometry.location;
map.setCenter(center);
new google.maps.Marker({ position: center, map: map });
map.setOptions({
center: center,
zoom: 14,
});
putting that into your existing code:
let map;
function initMap() {
const localContextMapView = new google.maps.localContext.LocalContextMapView({
element: document.getElementById("map"),
placeTypePreferences: ["restaurant", "tourist_attraction"],
maxPlaceCount: 12,
});
map = localContextMapView.map;
let geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: "1600 Amphitheatre Parkway, Mountain View, CA"
}, (results, status) => {
if (status === "OK") {
const center = results[0].geometry.location;
map.setCenter(center);
new google.maps.Marker({
position: center,
map: map
});
map.setOptions({
center: center,
zoom: 14,
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
updated fiddle
code snippet:
let map;
function initMap() {
const localContextMapView = new google.maps.localContext.LocalContextMapView({
element: document.getElementById("map"),
placeTypePreferences: ["restaurant", "tourist_attraction"],
maxPlaceCount: 12,
});
map = localContextMapView.map;
let geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: "1600 Amphitheatre Parkway, Mountain View, CA"
}, (results, status) => {
if (status === "OK") {
const center = results[0].geometry.location;
map.setCenter(center);
new google.maps.Marker({
position: center,
map: map
});
map.setOptions({
center: center,
zoom: 14,
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Local Context Basic</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=localContext&v=beta" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
</body>
</html>
Seems like you already have address and you just need to use geocoding API to convert the address into coordinates.
Inside of your script, you need to get geocoding API CDN with reloading the page. I will use axios to do that. Here is the code;
Add these two lines in the head of your HTML page.
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
Now you can make AJAX request using axios.
Inside your script;
axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=Your_address&key=YOUR_API_KEY`)
.then(response => {
var lt = response.geometry.location.lat;
var ln = response.geometry.location.lng;
map.setCenter({lat: lt, lng:ln});
marker.setCenter({lat: lt, lng: ln});
})
.catch(error => {
console.log(error) //or whatever you want
})

Google maps Snap to road demo not working | Google Maps API error: MissingKeyMapError

I am trying to get the Snap to Road demo working that is supplied here but I keep getting the error: Google Maps API error: MissingKeyMapError. I already searched around and this is the error Google gives you for either supplying no key or a invalid key but even if I generate a brand new key it won't work. It just gives me a blank screen.
Why is it throwing this error even though I supply the code with the API key?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Roads API Demo</title>
<style>
html,
body,
#map {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#bar {
width: 240px;
background-color: rgba(255, 255, 255, 0.75);
margin: 8px;
padding: 4px;
border-radius: 4px;
}
#autoc {
width: 100%;
box-sizing: border-box;
}
</style>
<script src="jquery-3.2.1.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places"></script>
<script>
var apiKey = 'AIzaSyB3kpx3fgR9VT3WL2tp49QrbnyDdgygGeo';
var map;
var drawingManager;
var placeIdArray = [];
var polylines = [];
var snappedCoordinates = [];
function initialize() {
var mapOptions = {
zoom: 17,
center: {
lat: -33.8667,
lng: 151.1955
}
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// Adds a Places search box. Searching for a place will center the map on that
// location.
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(
document.getElementById('bar'));
var autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autoc'));
autocomplete.bindTo('bounds', map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
});
// Enables the polyline drawing control. Click on the map to start drawing a
// polyline. Each click will add a new vertice. Double-click to stop drawing.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYLINE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYLINE
]
},
polylineOptions: {
strokeColor: '#696969',
strokeWeight: 2
}
});
drawingManager.setMap(map);
// Snap-to-road when the polyline is completed.
drawingManager.addListener('polylinecomplete', function(poly) {
var path = poly.getPath();
polylines.push(poly);
placeIdArray = [];
runSnapToRoad(path);
});
// Clear button. Click to remove all polylines.
$('#clear').click(function(ev) {
for (var i = 0; i < polylines.length; ++i) {
polylines[i].setMap(null);
}
polylines = [];
ev.preventDefault();
return false;
});
}
// Snap a user-created polyline to roads and draw the snapped path
function runSnapToRoad(path) {
var pathValues = [];
for (var i = 0; i < path.getLength(); i++) {
pathValues.push(path.getAt(i).toUrlValue());
}
$.get('https://roads.googleapis.com/v1/snapToRoads', {
interpolate: true,
key: apiKey,
path: pathValues.join('|')
}, function(data) {
processSnapToRoadResponse(data);
drawSnappedPolyline();
getAndDrawSpeedLimits();
});
}
// Store snapped polyline returned by the snap-to-road service.
function processSnapToRoadResponse(data) {
snappedCoordinates = [];
placeIdArray = [];
for (var i = 0; i < data.snappedPoints.length; i++) {
var latlng = new google.maps.LatLng(
data.snappedPoints[i].location.latitude,
data.snappedPoints[i].location.longitude);
snappedCoordinates.push(latlng);
placeIdArray.push(data.snappedPoints[i].placeId);
}
}
// Draws the snapped polyline (after processing snap-to-road response).
function drawSnappedPolyline() {
var snappedPolyline = new google.maps.Polyline({
path: snappedCoordinates,
strokeColor: 'black',
strokeWeight: 3
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
}
// Gets speed limits (for 100 segments at a time) and draws a polyline
// color-coded by speed limit. Must be called after processing snap-to-road
// response.
function getAndDrawSpeedLimits() {
for (var i = 0; i <= placeIdArray.length / 100; i++) {
// Ensure that no query exceeds the max 100 placeID limit.
var start = i * 100;
var end = Math.min((i + 1) * 100 - 1, placeIdArray.length);
drawSpeedLimits(start, end);
}
}
// Gets speed limits for a 100-segment path and draws a polyline color-coded by
// speed limit. Must be called after processing snap-to-road response.
function drawSpeedLimits(start, end) {
var placeIdQuery = '';
for (var i = start; i < end; i++) {
placeIdQuery += '&placeId=' + placeIdArray[i];
}
$.get('https://roads.googleapis.com/v1/speedLimits',
'key=' + apiKey + placeIdQuery,
function(speedData) {
processSpeedLimitResponse(speedData, start);
}
);
}
// Draw a polyline segment (up to 100 road segments) color-coded by speed limit.
function processSpeedLimitResponse(speedData, start) {
var end = start + speedData.speedLimits.length;
for (var i = 0; i < speedData.speedLimits.length - 1; i++) {
var speedLimit = speedData.speedLimits[i].speedLimit;
var color = getColorForSpeed(speedLimit);
// Take two points for a single-segment polyline.
var coords = snappedCoordinates.slice(start + i, start + i + 2);
var snappedPolyline = new google.maps.Polyline({
path: coords,
strokeColor: color,
strokeWeight: 6
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
}
}
function getColorForSpeed(speed_kph) {
if (speed_kph <= 40) {
return 'purple';
}
if (speed_kph <= 50) {
return 'blue';
}
if (speed_kph <= 60) {
return 'green';
}
if (speed_kph <= 80) {
return 'yellow';
}
if (speed_kph <= 100) {
return 'orange';
}
return 'red';
}
$(window).on('load', function() {
initialize
});
</script>
</head>
<body>
<div id="map"></div>
<div id="bar">
<p class="auto"><input type="text" id="autoc" /></p>
<p><a id="clear" href="#">Click here</a> to clear map.</p>
</div>
</body>
</html>
If you haven't got an API KEY:
The script element that loads the API is missing the required authentication parameter. If you are using the standard Maps JavaScript API, you must use a key parameter with a valid API key.
Step 1: Get a Key from this URL
https://developers.google.com/maps/documentation/javascript/get-api-key
Step 2: Include your script with the API KEY
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
type="text/javascript"></script>
Or replace
var apiKey = 'YOUR_API_KEY';
If you got an API KEY
Google maps Snap to Road demo
Full Code
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#bar {
width: 240px;
background-color: rgba(255, 255, 255, 0.75);
margin: 8px;
padding: 4px;
border-radius: 4px;
}
#autoc {
width: 100%;
box-sizing: border-box;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Roads API Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/_static/js/jquery-bundle.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places"></script>
<script>
var apiKey = 'AIzaSyB3kpx3fgR9VT3WL2tp49QrbnyDdgygGeo';
var map;
var drawingManager;
var placeIdArray = [];
var polylines = [];
var snappedCoordinates = [];
function initialize() {
var mapOptions = {
zoom: 17,
center: {lat: -33.8667, lng: 151.1955}
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// Adds a Places search box. Searching for a place will center the map on that
// location.
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(
document.getElementById('bar'));
var autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autoc'));
autocomplete.bindTo('bounds', map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
});
// Enables the polyline drawing control. Click on the map to start drawing a
// polyline. Each click will add a new vertice. Double-click to stop drawing.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYLINE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYLINE
]
},
polylineOptions: {
strokeColor: '#696969',
strokeWeight: 2
}
});
drawingManager.setMap(map);
// Snap-to-road when the polyline is completed.
drawingManager.addListener('polylinecomplete', function(poly) {
var path = poly.getPath();
polylines.push(poly);
placeIdArray = [];
runSnapToRoad(path);
});
// Clear button. Click to remove all polylines.
$('#clear').click(function(ev) {
for (var i = 0; i < polylines.length; ++i) {
polylines[i].setMap(null);
}
polylines = [];
ev.preventDefault();
return false;
});
}
// Snap a user-created polyline to roads and draw the snapped path
function runSnapToRoad(path) {
var pathValues = [];
for (var i = 0; i < path.getLength(); i++) {
pathValues.push(path.getAt(i).toUrlValue());
}
$.get('https://roads.googleapis.com/v1/snapToRoads', {
interpolate: true,
key: apiKey,
path: pathValues.join('|')
}, function(data) {
processSnapToRoadResponse(data);
drawSnappedPolyline();
getAndDrawSpeedLimits();
});
}
// Store snapped polyline returned by the snap-to-road service.
function processSnapToRoadResponse(data) {
snappedCoordinates = [];
placeIdArray = [];
for (var i = 0; i < data.snappedPoints.length; i++) {
var latlng = new google.maps.LatLng(
data.snappedPoints[i].location.latitude,
data.snappedPoints[i].location.longitude);
snappedCoordinates.push(latlng);
placeIdArray.push(data.snappedPoints[i].placeId);
}
}
// Draws the snapped polyline (after processing snap-to-road response).
function drawSnappedPolyline() {
var snappedPolyline = new google.maps.Polyline({
path: snappedCoordinates,
strokeColor: 'black',
strokeWeight: 3
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
}
// Gets speed limits (for 100 segments at a time) and draws a polyline
// color-coded by speed limit. Must be called after processing snap-to-road
// response.
function getAndDrawSpeedLimits() {
for (var i = 0; i <= placeIdArray.length / 100; i++) {
// Ensure that no query exceeds the max 100 placeID limit.
var start = i * 100;
var end = Math.min((i + 1) * 100 - 1, placeIdArray.length);
drawSpeedLimits(start, end);
}
}
// Gets speed limits for a 100-segment path and draws a polyline color-coded by
// speed limit. Must be called after processing snap-to-road response.
function drawSpeedLimits(start, end) {
var placeIdQuery = '';
for (var i = start; i < end; i++) {
placeIdQuery += '&placeId=' + placeIdArray[i];
}
$.get('https://roads.googleapis.com/v1/speedLimits',
'key=' + apiKey + placeIdQuery,
function(speedData) {
processSpeedLimitResponse(speedData, start);
}
);
}
// Draw a polyline segment (up to 100 road segments) color-coded by speed limit.
function processSpeedLimitResponse(speedData, start) {
var end = start + speedData.speedLimits.length;
for (var i = 0; i < speedData.speedLimits.length - 1; i++) {
var speedLimit = speedData.speedLimits[i].speedLimit;
var color = getColorForSpeed(speedLimit);
// Take two points for a single-segment polyline.
var coords = snappedCoordinates.slice(start + i, start + i + 2);
var snappedPolyline = new google.maps.Polyline({
path: coords,
strokeColor: color,
strokeWeight: 6
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
}
}
function getColorForSpeed(speed_kph) {
if (speed_kph <= 40) {
return 'purple';
}
if (speed_kph <= 50) {
return 'blue';
}
if (speed_kph <= 60) {
return 'green';
}
if (speed_kph <= 80) {
return 'yellow';
}
if (speed_kph <= 100) {
return 'orange';
}
return 'red';
}
$(window).load(initialize);
</script>
</head>
<body>
<div id="map"></div>
<div id="bar">
<p class="auto"><input type="text" id="autoc"/></p>
<p><a id="clear" href="#">Click here</a> to clear map.</p>
</div>
</body>
</html>

How to show duration trip in google map api

I'm using google map API to show the distance betewenn to points depending on the transportation and I like to show the duration of the trip like in the google map site (see the image). I'm using the v3 of google map and also the DirectionsRenderer function:
so far:
self.renderDirections = function (directions, status) {
self.cleanDisplayedDirections();
for (var i = 0, len = directions.routes.length; i < len && i < 3; i++) {
var direction = new google.maps.DirectionsRenderer({
map: map,
directions: directions,
routeIndex: i,
draggable: true,
suppressInfoWindows: false,
suppressMarkers: true
});
displayedDirections.push(direction);
}
};
Like in the image I would like to show, for instance, that is 13 min for the walk of 1 km.
Also, it is possible to change the polylineOptions for one route to be "dotted" like in the image?
EDIT: Okay, I have an answer to most of the components of your question.
(I kind of need this myself. I might as well write it now and post it here)
So I added a function that calculates a point, at a given distance, along a route. This is quite useful to place that infoWindow where you want it.
(probably a more elegant function could be written, but it does the trick)
You can take it from here, I guess. Just make var content as you need it to be. Add Walking/Driving image, ...
<!DOCTYPE html>
<html>
<head>
<title>How to show duration trip in google map api</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 90%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<input id="start" placeholder="start" value="Lausanne Gare">
<input id="end" placeholder="end" value="Chemin de Bellerive 32, 1007 Lausanne">
<input type="button" onclick="submit_form()" value="Calculate Route">
<script>
var directionsDisplayDriving;
var directionsDisplayWalking;
var infowindowDriving;
var infowindowWalking;
var directionsService;
var map;
// returns a polyline. Depending on the travelMode
function getPolylineOptions(travelMode) {
switch(travelMode) {
default:
case 'DRIVING':
return {
strokeColor: '#808080', // grey'ish
strokeOpacity: 1.0,
strokeWeight: 3
};
break;
case 'WALKING':
// Define a symbol using SVG path notation, with an opacity of 1.
var lineSymbol = {
path: 'M 0,-1 0,1',
strokeOpacity: 1,
scale: 3
};
// Create the polyline, passing the symbol in the 'icons' property.
// Give the line an opacity of 0.
// Repeat the symbol at intervals of 20 pixels to create the dashed effect.
return {
strokeColor: '#0099ff',
strokeOpacity: 0,
strokeWeight: 3,
icons: [{
icon: lineSymbol,
offset: '0',
repeat: '15px'
}]
};
break;
}
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 46.5138527, lng: 6.6260286}, // Lausanne
zoom: 12
});
directionsService = new google.maps.DirectionsService();
}
// reads the inputs and calculates the route
function submit_form() {
// remove previous routes
if(directionsDisplayDriving) {
directionsDisplayDriving.setMap(null);
directionsDisplayDriving = null;
}
if(directionsDisplayWalking) {
directionsDisplayWalking.setMap(null);
directionsDisplayWalking = null;
}
// calculate the route, both Driving and Walking
calcRoute(
document.getElementById('start').value,
document.getElementById('end').value,
'DRIVING',
function(display) {
// we put an infoWindow, 20% along the Driving route, and display the total length and duration in the content.
directionsDisplayDriving = display;
var point = distanceAlongPath(display, null, .2);
var content = 'Driving - total distance: ' + getTotalDistance(display) + 'm <br/> total duration: ' + getTotalDuration(display) +'s';
if(infowindowDriving) {
infowindowDriving.setMap(null);
}
infowindowDriving = new google.maps.InfoWindow({
content: content,
map: map,
position: point
});
}
);
calcRoute(
document.getElementById('start').value,
document.getElementById('end').value,
'WALKING',
function(display) {
// we put an infoWindow, 40% along the Walking route, and display the total length and duration in the content.
directionsDisplayWalking = display;
var point = distanceAlongPath(display, null, .4);
var content = 'Walking - total distance: ' + getTotalDistance(display) + 'm <br/> total duration: ' + getTotalDuration(display) +'s';
if(infowindowWalking) {
infowindowWalking.setMap(null);
}
infowindowWalking = new google.maps.InfoWindow({
content: content,
map: map,
position: point
});
}
);
////absolute (in meter)
//var point = distanceAlongPath(directionsDisplay, 100000);
// as a ratio (0 to 1) of the route
//var point = distanceAlongPath(directionsDisplay, null, 0.3); // at 30% from the origin
}
function calcRoute(start, end, travelMode, onReady) {
// alert(travelMode);
var mode = google.maps.TravelMode[travelMode];
var request = {
origin: start,
destination: end,
travelMode: mode
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var polylineOptions = getPolylineOptions(travelMode);
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true,
map: map,
polylineOptions: polylineOptions,
preserveViewport: false
});
directionsDisplay.setDirections(response);
if(typeof onReady == 'function') {
onReady(directionsDisplay);
}
}
else {
console.log('status: ' + status);
}
});
}
function getTotalDuration(directionsDisplay) {
var directionsResult = directionsDisplay.getDirections();
var route = directionsResult.routes[0];
var totalDuration = 0;
var legs = route.legs;
for(var i=0; i<legs.length; ++i) {
totalDuration += legs[i].duration.value;
}
return totalDuration;
}
function getTotalDistance(directionsDisplay) {
var directionsResult = directionsDisplay.getDirections();
var route = directionsResult.routes[0];
var totalDistance = 0;
var legs = route.legs;
for(var i=0; i<legs.length; ++i) {
totalDistance += legs[i].distance.value;
}
return totalDistance;
}
// Returns a point along a route; at a requested distance ( either absolute (in meter) or as a ratio (0 to 1) of the route)
// example : you have a random route ( 100km long), and you want to put a marker, 30km from the origin.
// we add the distances of the waypoints and stop when we reach the requested total length.
// nothing stops you from making it even more precise by interpolling.
// the function returns a location (LatLng) along the route
function distanceAlongPath(directionsDisplay, distanceFromOrigin, ratioFromOrigin) {
var directionsResult = directionsDisplay.getDirections();
var route = directionsResult.routes[0];
var totalDistance = getTotalDistance(directionsDisplay);
var tempDistanceSum = 0;
var dist = 0;
if(ratioFromOrigin) {
distanceFromOrigin = ratioFromOrigin * totalDistance;
}
// we prepare the object
var result = new Object();
result.routes = new Array();
result.routes[0] = route;
for(var i in result.routes[0].overview_path) {
if (i>0) {
dist = google.maps.geometry.spherical.computeDistanceBetween (result.routes[0].overview_path[i], result.routes[0].overview_path[i - 1]);
}
tempDistanceSum += dist;
if (tempDistanceSum > distanceFromOrigin) {
return result.routes[0].overview_path[i];
}
// console.log(dist+' '+tempDistanceSum);
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap&libraries=geometry" async defer></script>
</body>
</html>
(FIRST submitted, might be interesting for the details of the dashed polylines)
Also, it is possible to change the polylineOptions for one route to be "dotted" like in the image?
Here is part of your question.
A Select box has
DRIVING: with a normal polyline (I gave it some color)
WALKING: with a dashed polyline. I suppose you should try out different numbers, to get the lineType right.
<!DOCTYPE html>
<html>
<head>
<title>Google Maps - Dashed polylines</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 90%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<input id="start" placeholder="start" value="Brussels">
<input id="end" placeholder="end" value="Paris">
<select id="mode">
<option value="DRIVING">DRIVING</option>
<option value="WALKING">WALKING</option>
</select>
<input type="button" onclick="submit_form()" value="Calculate Route">
<script>
var directionsDisplay;
var directionsService;
var map;
// returns a polyline. Depending on the travelMode
function getPolylineOptions(travelMode) {
// alert(travelMode);
switch(travelMode) {
default:
case 'DRIVING':
return {
strokeColor: '#808080', // grey'ish
strokeOpacity: 1.0,
strokeWeight: 3
};
break;
case 'WALKING':
// Define a symbol using SVG path notation, with an opacity of 1.
var lineSymbol = {
path: 'M 0,-1 0,1',
strokeOpacity: 1,
scale: 4
};
// Create the polyline, passing the symbol in the 'icons' property.
// Give the line an opacity of 0.
// Repeat the symbol at intervals of 20 pixels to create the dashed effect.
return {
strokeColor: '#ff0000', // red
strokeOpacity: 0,
//strokeWeight: 3,
icons: [{
icon: lineSymbol,
offset: '0',
repeat: '20px'
}]
};
break;
}
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 50.869754630095834, lng: 4.353812903165801}, // Brussels
zoom: 12
});
directionsService = new google.maps.DirectionsService();
}
// reads the inputs and calculates the route
function submit_form() {
calcRoute(
document.getElementById('start').value,
document.getElementById('end').value,
document.getElementById('mode').value
)
}
function calcRoute(start, end, travelMode) {
// alert(travelMode);
var mode = google.maps.TravelMode[travelMode];
var request = {
origin: start,
destination: end,
travelMode: mode
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var polylineOptions = getPolylineOptions(travelMode);
// you might want to remove the previous polyline. If not, don't add this
if(directionsDisplay) {
directionsDisplay.setMap(null);
}
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true,
map: map,
polylineOptions: polylineOptions,
preserveViewport: false
});
directionsDisplay.setDirections(response);
}
else {
console.log('status: ' + status);
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</body>
</html>

Google Maps API finding area by address

In my application I want to group items addresses by areas, my items already use Google maps API to choose address and has Lat/Long coordinates. I want to group them by areas automatically.
The example would be
If we have address https://www.google.com/maps/place/Erfurto+g.+1,+Vilnius+04220,+Lietuva/#54.6765968,25.2102183,15.5z/data=!4m2!3m1!1s0x46dd9398506f84bd:0x6cc62f1d26bc6613
It should automatically be assigned to area, marked here:
https://www.google.com/maps/place/Lazdynai,+Vilnius,+Lietuva/#54.6702541,25.1870655,14z/data=!4m2!3m1!1s0x46dd93a6cc53ba05:0x2600d18d4c454331
Areas should be also administered in my application.
As I understand I should store all MultiPolygon coordinates in my back-end, and then use some algorithm to find if the coordinates of address belong to that polygon? Am I right? Or I can fetch that somehow using Google Map API?
I made some very rough polygons (sorry if I insult anybody from Vilnius :) ), but I think you'll get the idea.
the main method you're looking for is google.maps.geometry.poly.containsLocation()
So I think this gives you the components you need; the plinciles. But if there is something specific you want to happen, please tell me.
<!DOCTYPE html>
<html>
<head>
<style>
html, body, #map-canvas {
height: 400px;
margin: 0px;
padding: 0px
}
#my_div {
border: 1px solid grey;
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<script>
// these are very rough estimations of the Elderships of Vilnius
// please use the correct boundaries
var polygonData = [
{name: 'Senamiestis', color: '#ff0000', points: [[54.68256489008578, 25.315074920654297],[54.67631238544733, 25.30803680419922],[54.670555259971174, 25.288639068603516],[54.6752205795425, 25.269927978515625],[54.68812186362444, 25.259113311767578],[54.69506701073871, 25.26529312133789],[54.68832031289468, 25.30099868774414]]},
{name: 'Rasos', color: '#00ff00', points: [[54.669066215366605, 25.305633544921875],[54.68554193480844, 25.329322814941406],[54.68335879002739, 25.362625122070312],[54.656754688760536, 25.345458984375],[54.610254981579146, 25.328292846679688],[54.60568162741719, 25.308380126953125],[54.65516583289068, 25.29705047607422]]},
{name: 'Antakalnis', color: '#0000ff', points: [[54.72699938009521, 25.30426025390625],[54.71589532099472, 25.34820556640625],[54.80780860259057, 25.500640869140625],[54.81967870427071, 25.335845947265625],[54.771385204918595, 25.300140380859375]]}
];
var polygons = [];
var map;
// random markers.
var markerData = [
[54.75478050308602,25.3638149499893],
[54.68324427673198,25.27517330646513],
[54.70583916710748,25.240154385566694],
[54.68453433466152,25.293562531471235],
[54.72900384013322,25.330534100532514],
[54.682078227560325,25.28394949436186],
[54.65034635955749,25.30793917179106]
];
var markers = [];
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(54.682611637187925,25.287838697433454), // Vilnius university
mapTypeId: google.maps.MapTypeId.ROADMAP
};
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// draw the markers
var markerLocations = toLatLng(markerData);
for(var i in markerLocations) {
markers.push( new google.maps.Marker({
position: markerLocations[i],
title: i, // I'll just set the index as title.
map: map
}) );
}
// draw the polygons
for(var j in polygonData) {
var points = toLatLng(polygonData[j].points);
polygons[j] = drawPolygon(points, polygonData[j].color, polygonData[j].name);
// let's see if markers are in this polygon
var content = '';
for(var i in markerLocations) {
if (google.maps.geometry.poly.containsLocation(markers[i].position, polygons[j])) {
// display
content += '<li>' + markers[i].title + '</li>';
// I guess what you really want to do, is put this data in an array, or so
}
}
document.getElementById('display-data').innerHTML += '<h3>' + polygonData[j].name + '</h3>' + '<ul>' + content + '</ul><hr/>';
}
}
// takes an array of coordinats, [ [], [], [] ] , and returns Google Maps LatLng objects
function toLatLng(point_arrays) {
var locations = [];
for(var i in point_arrays) {
locations.push( new google.maps.LatLng(point_arrays[i][0], point_arrays[i][1]));
}
return locations;
}
// draws a polygon
function drawPolygon(points, color, name) {
if(points.length < 3) {
return;
}
// #see https://developers.google.com/maps/documentation/javascript/examples/polygon-simple
polygon = new google.maps.Polygon({
paths: points,
strokeColor: color,
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: color,
fillOpacity: 0.35,
title: name,
map: map
});
return polygon;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
ul, li {
list-style: none;
}
li {
display: inline;
border: 1px solid grey;
padding: 5px;
margin: 5px;
}
</style>
</head>
<body>
<div id="map-canvas"></div>
<div id="display-data"></div>
</body>
</html>
What you could do, is update the markers table in the database; add a field 'eldership'.
You send the data you get from my script to the server, with Ajax, you update the table (= you fill in the id of the eldership in the eldership field of the marker), so you only have to do this once (and you need to update the new markers ...).