Google Maps API finding area by address - google-maps

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 ...).

Related

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

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>

How to directly identify the co ordinates of a city in google maps?

I am trying to achieve the following
home page: visitor will search for a city or location from the search field. The zoom level as per google documentation is below.
1: World
5: Landmass/continent
10: City
15: Streets
20: Buildings
On Search Page: I want to list all the properties which is there in the locality searched e.g. California so i want to show all the properties on map with the Zoom level 10 .. but the issue is i am struggling to find the co ordinates of the city.. do i have to add all the cities co ordinates in the database? see below code.. how can i make center: {lat: 19.1760, lng: 72.7954} dynamic so it changes accordingly.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
/* 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;
}
</style>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBkyMvhWRirAMPvBnjgzXEH6DIkjwXwW_A&callback=initMap">
</script>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 19.1760, lng: 72.7954}
});
setMarkers(map);
}
var beaches = [
['Aksa Beach', 19.1760, 72.7954, 1],
['Juhu Beach', 19.0969, 72.8266, 1]
];
function setMarkers(map) {
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
for (var i = 0; i < beaches.length; i++) {
var beach = beaches[i];
var marker = new google.maps.Marker({
position: {lat: beach[1], lng: beach[2]},
map: map,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
marker.addListener('click', function() {
map.setZoom(20);
map.setCenter(marker.getPosition());
});
}
}
</script>
</body>
</html>
So in short how can i get the co ordinates of the city/continent/streen etc dynamically to render the map? as co ordinates are required attributes.
Use geocoder.
geocoder.geocode( { 'address': Address_text}, function(results, status) {
if (status== google.maps.GeocoderStatus.OK) {
loc_lat = results[0].geometry.location.lat();
loc_lon = results[0].geometry.location.lng()]
fmaddress = results[0].formatted_address;
alert('LAT: '+loc_lat+', LON: '+loc_lon+' ADDRESS: '+fmaddress);
} else {
if(Address_text != '' && Address_text!= null) {
alert('Couldnt get the X,Y');
}
}
});
Note, you wont be able to use location lat,lon, address, until the request is over, you have to wait for the request to get back, then use the data. Since JS works in asynchronous way. Dont forget to use '&libraries=places'. ->
https://maps.googleapis.com/maps/api/js?key=AIzaSyBkyMvhWRirAMPvBnjgzXEH6DIkjwXwW_A&libraries=places&callback=initMap

create a polyline with multiple points, then join an added marker to a line segment google maps v3

I have a google map that I am plotting a route on and linking my points with a polyline. I create a new point on the line with a right click on the map. I also have the ability to create a point of interest along my path and I'm using a different marker icon for those as well as showing an info window with the POI text.
google.maps.event.addListener(Map, "rightclick", function (event) {
var markerIndex = polyLine.getPath().length;
polyLine.setMap(Map);
var isFirstMarker = markerIndex === 0;
var marker;
var poiText = "";
if(!isAddingPOI) {
marker = new google.maps.Marker({
map: Map,
position: event.latLng,
draggable: true,
icon: '/images/waypoint.png'
});
} else {
poiText = prompt("Enter a short description for this point of interest", "");
if (poiText != null) {
marker = new google.maps.Marker({
map: Map,
position: event.latLng,
draggable: true,
icon: '/images/point_of_interest.png',
info: new google.maps.InfoWindow({
content:poiText
})
});
}
}
if (isAddingPOI) {
predefinedPositions.push(new predefinedPosition(event.latLng.lat(), event.latLng.lng(), poiText));
google.maps.event.addListener(marker, 'click', function () {
marker.info.open(Map, marker);
});
isAddingPOI = false;
} else {
predefinedPositions.push(new predefinedPosition(event.latLng.lat(), event.latLng.lng()));
}
polyLine.getPath().push(event.latLng);
outlineMarkers.push(marker);
google.maps.event.addListener(marker, 'drag', function (dragEvent) {
polyLine.getPath().setAt(markerIndex, dragEvent.latLng);
predefinedPositions[markerIndex].Latitude = dragEvent.latLng.lat();
predefinedPositions[markerIndex].Longitude = dragEvent.latLng.lng();
updateDistance(outlineMarkers);
});
updateDistance(outlineMarkers);
});
what I need now is the ability for the user to specify a LatLng for a new marker which would be placed on the map as draggable and then to be able to merge (by dragging) that marker to my created path. Ideally, I'd like for the segment of the polyline where the marker is dragged to change colors while the marker is over it. I'll then need to add that marker to the path array for the final output.
I found this which is the closest to what I want that I could find but it's not quite what I'm looking for: Google Maps API v3 - Draggable Marker Along a Polyline
I also tried adding a 'mouseover' event to my polyline to update the color which doesn't ever get triggered while I'm dragging a marker. It also updates the entire polyline's color (not just the segment) when I mouse over it. I'm sure I can sort out the segment color change myself, but I'm stuck on dragging the marker over the line and having it change colors and ultimately merging it to my path.
any suggestions would be greatly appreciated.
TIA
I got it sorted out using something similar to this: Confine dragging of Google Maps V3 Marker to Polyline
I didn't get the polyline segment to change colors, but this "snap-to" functionality is really close to what I was looking for.
try this way
//data sample
var cities = [
{
city : 'Mayestik Tailor',
desc : 'Jln Aspal Rata',
lat : -6.2426373,
lng : 106.7907953
},
{
city : 'Bubur Ayam Barito',
desc : 'Jl. Gandaria Tengah 3, Kramat Pela, Kebayoran Baru',
lat : -6.2457674,
lng : 106.790865
},
{
city : 'Apartment Permata Gandaria',
desc : 'Jl. Kyai Moh. Syafii Hadzami/Jl. Taman Gandaria',
lat : -6.2450461,
lng : 106.7882604
}
];
create function to center point of layout
var mapOptions = {
zoom: 15,
center:new google.maps.LatLng(-6.2451528,106.7901808),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var createMarker = function (info){
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(info.lat, info.lng),
title: info.city
});
}
var arr = [];
for (i = 0; i < cities.length; i++){
arr.push(new google.maps.LatLng(cities[i].lat, cities[i].lng));
}
// create polyline
var flightPath = new google.maps.Polyline({
path: arr,
geodesic: true,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
// loop for marker
for (i = 0; i < cities.length; i++){
createMarker(cities[i]);
}
for css class
#map {
height:420px;
width:600px;
}
.infoWindowContent {
font-size: 14px !important;
border-top: 1px solid #ccc;
padding-top: 10px;
}
h2 {
margin-bottom:0;
margin-top: 0;
}
on HTML Code
<div id="map"></div>

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 Map: How can I select multiple markers, which I imported, by clicking or drawing a shape around them and save them as a Data Table?

I created a map with Google Map Maker. I did so by imported 5 different Excel files that had address fields and saved them all as different layers. The map now has about 500 addresses which are marked with pins that are color coded to the layer they belong with. I have no code per say, just the my Google Map which I created.
Is there anyway I can either use the "Draw Line" tool or another means to select a group of those markers/pins? Ideally I am envisioning being able to draw a shape around them and then being able to select those address to save them as a new data table or layer to export back to Excel.
Does anyone know of a way to achieve this? Even if it is another product then Google Maps? Thank you so much any help would be a life saver.
Something like this.
<head>
<style>
html, body, #map-canvas {
height: 400px;
margin: 0px;
padding: 0px
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<script>
var random_marker_locations = [
new google.maps.LatLng(50.7, 4.1),
new google.maps.LatLng(50.4, 4.2),
new google.maps.LatLng(50.1, 4.3),
new google.maps.LatLng(50.8, 4.4),
new google.maps.LatLng(50.5, 4.5),
new google.maps.LatLng(50.2, 4.6),
new google.maps.LatLng(50.9, 4.7),
new google.maps.LatLng(50.6, 4.8),
new google.maps.LatLng(50.3, 4.9)
]
var map;
var markers = [];
var polygon;
var polygonMarkers = [];
var polygonLocations = [];
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(50.40, 4.34), // Brussels, Belgium
mapTypeId: google.maps.MapTypeId.ROADMAP
};
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// add markers
for(var i in random_marker_locations) {
var marker = new google.maps.Marker({position: random_marker_locations[i], map: map, title: 'marker ' + i});
markers.push(marker);
}
// add a click on map event
google.maps.event.addListener(map, 'click', function(e) {
// set a marker there, with a small measle icon
var position = e.latLng;
polygonLocations.push(position);
polygonMarkers.push(new google.maps.Marker({
icon: 'https://maps.gstatic.com/intl/en_ALL/mapfiles/markers2/measle.png',
position: position,
map: map
}));
// now let's add a polygon
drawPolygon(polygonLocations);
});
}
// draws a polygon
function drawPolygon(points) {
if(points.length < 3) {
return;
}
// first delete the previous polygon
if(polygon) {
polygon.setMap(null);
}
// #see https://developers.google.com/maps/documentation/javascript/examples/polygon-simple
polygon = new google.maps.Polygon({
paths: points,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map
});
// display to input
displaySelectedMarkers(polygon);
}
// display the selected markers to input.
function displaySelectedMarkers(polygon) {
// empty the input
document.getElementById('selected_markers').value = '';
var a=0; // I use this to set a comma between the values, but no comma at the end
for(var i in random_marker_locations) {
// #see https://developers.google.com/maps/documentation/javascript/examples/poly-containsLocation
if (google.maps.geometry.poly.containsLocation(random_marker_locations[i], polygon)) {
document.getElementById('selected_markers').value += (a++>0 ? ', ' : '') + i ;
}
}
}
function clearSelection() {
if(polygon) {
polygon.setMap(null);
}
for (var i in polygonMarkers) {
polygonMarkers[i].setMap(null);
}
polygonLocations = [];
document.getElementById('selected_markers').value = '';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<hr>
<input id="selected_markers"><br>
<input type="button" onclick="clearSelection()" value="Clear polygon"><br>
Click to select a polygon selection around the markers
</body>