Google api v3 show nearby markers on customer road - javascript

How can I show only the markers (they are predefined, but hidden for the whole map), which are nearby (may by radius of 10mile or 20mile) to the road I choose using Google api v3 for example I use Directions service
HTML:
<div id="panel">
<b>start: </b>
<input type="text" id="start" name="start" maxlength="30" onchange="calcRoute();" />
<b>end: </b>
<input type="text" id="end" name="end" maxlength="30" onchange="calcRoute();" />
</div>
<div id="map"></div>
JavaScript:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.891224, -87.638675);
var mapOptions = {
zoom:7,
center: chicago
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
/* === markers === */
var locations = [
['1', 40.577651, -82.200443],
['2', 40.760976, -93.911868],
['3', 39.110017, -111.116458],
['4', 27.036116, -81.717045],
['5', 34.104058, -117.444583],
['6', 44.790790, -121.443607],
];
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
map: map,
title: locations[i][0],
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
//visible: false, //true for all, but hidden
icon:'img/the_icon.png'
});
}
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);

You have 2 markers within 20 miles of a route from NY to LA:
example fiddle using RouteBoxer
function calcRoute() {
// Clear any previous route boxes from the map
clearBoxes();
// Convert the distance to box around the route from miles to km
distance = 20 * 1.609344;
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
// Box around the overview path of the first route
var path = response.routes[0].overview_path;
var boxes = routeBoxer.box(path, distance);
drawBoxes(boxes);
} else alert("Directions request failed: " + status);
});
}
// Draw the array of boxes as polylines on the map
function drawBoxes(boxes) {
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 1,
map: map
});
for (var j=0; j< gmarkers.length; j++) {
if (boxes[i].contains(gmarkers[j].getPosition()))
gmarkers[j].setMap(map);
}
}
}

Example using JSTS (from this question: How to draw a polygon around a polyline in JavaScript?. Uses google.maps.geometry.poly.containsLocation
code:
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var overviewPath = response.routes[0].overview_path,
overviewPathGeo = [];
for (var i = 0; i < overviewPath.length; i++) {
overviewPathGeo.push(
[overviewPath[i].lng(), overviewPath[i].lat()]);
}
var distance = 10 / 111.12, // Roughly 10km
geoInput = {
type: "LineString",
coordinates: overviewPathGeo
};
var geoInput = googleMaps2JTS(overviewPath);
var geometryFactory = new jsts.geom.GeometryFactory();
var shell = geometryFactory.createLineString(geoInput);
var polygon = shell.buffer(distance);
var oLanLng = [];
var oCoordinates;
oCoordinates = polygon.shell.points[0];
for (i = 0; i < oCoordinates.length; i++) {
var oItem;
oItem = oCoordinates[i];
oLanLng.push(new google.maps.LatLng(oItem[1], oItem[0]));
}
if (routePolygon && routePolygon.setMap) routePolygon.setMap(null);
routePolygon = new google.maps.Polygon({
paths: jsts2googleMaps(polygon),
map: map
});
for (var j=0; j< gmarkers.length; j++) {
if (google.maps.geometry.poly.containsLocation(gmarkers[j].getPosition(),routePolygon)) {
gmarkers[j].setMap(map);
} else {
gmarkers[j].setMap(null);
}
}
}
});
}

Related

Change the color between waypoints and fit the route to moved map marker

I use the google maps api to draw a route in a embedded google map. I changed the color of the hole route but I also would like to change the color between the waypoints for example:
Start --orange--> firstWP --red-- > secondWP --orange--> firstWP --red--> secondWp --orange--> Destination
The color between firstWP to seceondWP should be changed but secondWP to FirstWP sould be the same color as the other parts of the route.
Furthermore I also need to move the map markers and the route should move/change
fitting to the new position of the map marker but keep the different color.
This is a minimal example with draggable map marker and changed color between waypoints but the route does not adapt to the new position of the map markers
var map;
var directionsService;
var directionsDisplay;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
suppressPolylines: true
});
calcRoute(39.2903848, -76.6121893, 42.3600825, -71.05888);
}
google.maps.event.addDomListener(window, "load", initialize);
function calcRoute(origin_lat, origin_lng, destination_lat, destination_lng) {
console.log("Entrée CALC ROUTE");
var origin = new google.maps.LatLng(origin_lat, origin_lng);
var destination = new google.maps.LatLng(destination_lat, destination_lng);
var waypointsArray = document.getElementById('waypoints').value.split("|");
var waypts = [];
for (i = 0; i < waypointsArray.length; i++) {
if (waypointsArray[i] != "") {
var waypoint = waypointsArray[i];
var waypointArray = waypoint.split(",");
var waypointLat = waypointArray[0];
var waypointLng = waypointArray[1];
console.log("waypts lat " + waypointLat);
console.log("waypts lng " + waypointLng);
waypts.push({
location: new google.maps.LatLng(waypointLat, waypointLng),
stopover: true
})
}
}
console.log("waypts " + waypts.length);
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
waypoints: waypts,
provideRouteAlternatives: true
};
console.log("Calc request " + JSON.stringify(request));
directionsService.route(request, customDirectionsRenderer);
}
function customDirectionsRenderer(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var polyline = new google.maps.Polyline({map:map, strokeColor: "blue", path:[]})
if (i == 1) {
polyline.setOptions({strokeColor: "red"});
}
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
}
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<input id="waypoints" value="39.9525839,-75.1652215|40.7127837,-74.0059413" />
<div id="map_canvas"></div>
http://jsfiddle.net/westify/vop9o1n5/1/
Is it possible to do that? Or is it only possible if rerender the whole route after moved one waypoint?
One option would be to listen for the directions_changed event on the DirectionsRenderer, when that fires, redraw the directions polylines.
var firstTime = true;
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
console.log("directions changed firstTime=" + firstTime);
// prevent infinite loop
if (firstTime) {
google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed', function() {
console.log("directions changed");
customDirectionsRenderer(directionsDisplay.getDirections(), "OK");
});
}
firstTime = !firstTime;
});
proof of concept fiddle
code snippet:
var map;
var directionsService;
var directionsDisplay;
var firstTime = true;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
suppressPolylines: true
});
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
console.log("directions changed firstTime=" + firstTime);
if (firstTime) {
google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed', function() {
console.log("directions changed"); //+JSON.stringify(directionsDisplay.getDirections()));
customDirectionsRenderer(directionsDisplay.getDirections(), "OK");
});
}
firstTime = !firstTime;
});
calcRoute(39.2903848, -76.6121893, 42.3600825, -71.05888);
}
google.maps.event.addDomListener(window, "load", initialize);
function calcRoute(origin_lat, origin_lng, destination_lat, destination_lng) {
console.log("Entrée CALC ROUTE");
var origin = new google.maps.LatLng(origin_lat, origin_lng);
var destination = new google.maps.LatLng(destination_lat, destination_lng);
var waypointsArray = document.getElementById('waypoints').value.split("|");
var waypts = [];
for (i = 0; i < waypointsArray.length; i++) {
if (waypointsArray[i] != "") {
var waypoint = waypointsArray[i];
var waypointArray = waypoint.split(",");
var waypointLat = waypointArray[0];
var waypointLng = waypointArray[1];
console.log("waypts lat " + waypointLat);
console.log("waypts lng " + waypointLng);
waypts.push({
location: new google.maps.LatLng(waypointLat, waypointLng),
stopover: true
})
}
}
console.log("waypts " + waypts.length);
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
waypoints: waypts,
provideRouteAlternatives: true
};
console.log("Calc request " + JSON.stringify(request));
directionsService.route(request, customDirectionsRenderer);
}
var polylines = [];
function customDirectionsRenderer(response, status) {
for (var i = 0; i < polylines.length; i++) {
polylines[i].setMap(null);
}
polylines = [];
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var polyline = new google.maps.Polyline({
map: map,
strokeColor: "blue",
path: []
});
polylines.push(polyline);
if (i == 1) {
polyline.setOptions({
strokeColor: "red"
});
}
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
}
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="waypoints" value="39.9525839,-75.1652215|40.7127837,-74.0059413" />
<div id="map_canvas"></div>

combine the DirectionsService and PlacesService in google map

How to combine the DirectionsService and PlacesService in google map. I will inspire on this path http://www.indiaproperty.com/godrej-palm-grove-in-poonamallee-chennai-pl4110632?fr=sres2 . I can't get the duration & distance of each location. I need to find each location distance and duration. I given the code below:
var map;
var infowindow;
var markersArray = [];
var pyrmont = new google.maps.LatLng(20.268455824834792, 85.84099235520011);
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var places = [];
// var waypoints = [];
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 14,
zoomControl: false,
scaleControl: false,
scrollwheel: false,
disableDoubleClickZoom: true,
});
infowindow = new google.maps.InfoWindow();
//document.getElementById('directionsPanel').innerHTML='';
search_types();
}
function createMarker(place,icon) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon,
visible:true
});
markersArray.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("<b>Name:</b>"+place.name+"<br><b>Address:</b>"+place.vicinity+"<br><b>Reference:</b>"+place.reference+"<br><b>Rating:</b>"+place.rating+"<br><b>Id:</b>"+place.id);
infowindow.open(map, this);
});
}
var source="";
var dest='';
function search_types(latLng){
clearOverlays();
if(!latLng){
var latLng = pyrmont;
}
var placename = $('.nearby h3').attr("data-value")
var type = $('#valueStored').val();
var icon = "images/"+type+".png";
var request = {
location: latLng,
radius: 2000,
types: [type], //e.g. school, restaurant,bank,bar,city_hall,gym,night_club,park,zoo
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
$('.map-list').find('li').remove();
var service = new google.maps.places.PlacesService(map);
service.search(request, function(results, status) {
map.setZoom(14);
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
results[i].html_attributions='';
places[i] = results[i];
createMarker(results[i],icon);
$('.map-list').append('<li>'+results[i].name+'<div><span class="distance"></span> <span class="duration"></span></div></li>');
}
}
});
distanceCalc();
}
var latadd, longadd;
function distanceCalc(latLng){
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
var changeaddress;
var pyrmont1 = new google.maps.LatLng(20.268455824834792, 85.84099235520011);
var request = {
origin: pyrmont,
destination: pyrmont1,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var listed = $('.map-list li');
console.log(places[4]);
for (var i = 0; i < listed.length; i++) {
$('.distance').text(response.routes[0].legs[0].distance.value);
$('.duration').text(response.routes[0].legs[0].duration.value);
}
// Display the distance:
directionsDisplay.setDirections(response);
}
});
}
function showResult(result) {
latadd = result.geometry.location.lat();
longadd = result.geometry.location.lng();
}
// Deletes all markers in the array by removing references to them
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(false)
}
//markersArray.length = 0;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
function clearMarkers(){
$('#show_btn').show();
$('#hide_btn').hide();
clearOverlays()
}
function showMarkers(){
$('#show_btn').hide();
$('#hide_btn').show();
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(true)
}
}
}

Unexplained extra Polyline drawn - Google Maps API v3

I have a strange scenario with regards to a Polyline that is being drawn on the map. Before I post the code, I'll first demonstrate what happens when I make use of the normal direction services (Both calculates the resulting disctance the same = Total Distance: 62.734 km):
Now, when I draw the directions myself - this straight line appears out of nowhere:
Code snippet:
<script type="text/javascript">
var markers = [
{
"lat": '-26.2036247253418',
"lng": '28.0086193084717'
}
,
{
"lat": '-26.1259479522705',
"lng": '27.9742794036865'
}
,
{
"lat": '-25.8434619903564',
"lng": '28.2100086212158'
}
];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;
var totalDistance = 0;
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
//var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title,
label: labels[labelIndex++ % labels.length],
//icon: image
});
latlngbounds.extend(marker.position);
(function (marker, data) {
// google.maps.event.addListener(marker, "click", function (e) {
// infoWindow.setContent(data.description);
// infoWindow.open(map, marker);
// });
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
setMap: map
});
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
path.push(src);
//poly.strokeColor = '#'+Math.floor(Math.random()*16777215).toString(16);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
var myroute = directionsDisplay.directions.routes[0];
var distance = 0;
for (i = 0; i < myroute.legs.length; i++) {
distance += myroute.legs[i].distance.value;
//for each 'leg'(route between two waypoints) we get the distance and add it to the total
}
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
//console.log(result.routes[0].legs[0].distance);
}
totalDistance += distance;
document.getElementById('total').innerHTML = (totalDistance / 1000) + ' km';
}
});
}
}
}
</script>
<div id="dvMap"></div>
<div><p>Total Distance: <span id="total"></span></p></div>
Ok, so to solve the problem. Just remove the following line:
Reference: Google Documentation - Simple Polylines
And like that, the line is gone:
Aren't you also drawing a line between the first and last poly?
You should only draw lines between poly0 and poly1, poly1 and poly2 etc. but not poly100 and poly0 (if poly100 is the last one)
That would explain the straight line going from point B to A completing the shape. you don't want to complete the shape, so stop drawing. is there no function you can set to not complete the shape?
I only know of a very expensive work around and that is to trace back in reverse order from B to A along the same route. But that is probably not what you are looking for

Clear Polyline from Google Maps and then restart it

I am playing around with the Google Maps API v3 for a project I am building.The premise is the user can draw a route on the map however at any point can clear it and start again. The issue I am having is restarting the polyline after the map has been cleared. Whilst the markers appear the polyline does not.
I have discovered that the line poly.setMap(null); only hides the polyline that is draw and doesn't clear it therefore it is understandable why the line doesn't show. However on finding this out I now need to know how to clear it and how it can be restarted.
The code is below:
var poly;
var map, path = new google.maps.MVCArray(),
service = new google.maps.DirectionsService(), poly;
var removepolyline;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
var count = 0;
var countname = 0;
var latitude_start;
var longitude_start;
function initialize() {
var mapOptions = {
zoom: 16,
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
geocoder = new google.maps.Geocoder();
///Geolocation
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
///Place fallback loop
}
///Allows the polyline to follow the road
poly = new google.maps.Polyline({ map: map });
google.maps.event.addListener(map, "click", function(evt) {
if (path.getLength() === 0) {
//Enters on first click
path.push(evt.latLng);
poly.setPath(path);
} else {
//Enters on second click
service.route({
origin: path.getAt(path.getLength() - 1),
destination: evt.latLng,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length;
i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
var latitude_longitude = evt.latLng;
var latitude = evt.latLng.lat();
var longitude = evt.latLng.lng();
//alert(latitude_longitude);
//alert(latitude);
// alert(longitude);
///Saves the first click location
if(count === 0){
var latitude_start = evt.latLng.lat();
var longitude_start = evt.latLng.lng();
var firstlat = latitude_start;
var firstlng = longitude_start;
/////Trying to calculate distance
var origin1 = new google.maps.LatLng(firstlat, firstlng);///1st click - never changes
document.getElementById("origin1").value = origin1;
document.getElementById("startpoint").value = origin1;
////Calculate distance
var destinationA = new google.maps.LatLng(latitude, longitude); ///Most recent click
document.getElementById("destination").value = destinationA; ////Stores Destination
var origin1 = document.getElementsByName('origin1')[0].value ////Retrieves value from text box
count ++;
}else{
var origin1 = document.getElementsByName('destination')[0].value ////Retrieves value from text box
////Calculate distance
var destinationA = new google.maps.LatLng(latitude, longitude); ///Most recent click
document.getElementById("destination").value = destinationA; ////Stores Destination
}
////Calculate distance
var servicetime = new google.maps.DistanceMatrixService();
servicetime.getDistanceMatrix(
{
origins: [origin1],
destinations: [destinationA],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
}, callback);
});
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
///Enters the if it is the first loop round/first click
if(countname === 0){
document.getElementById("startpointname").value = origins;
countname ++;
}
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
//deleteOverlays(); ////
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
//addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
outputDiv.innerHTML += start + ' to ' + destinations[j]
+ ': ' + miles + ' miles in '
+ overalltime + ' minutes <br>';
}
}
}
}
// Add a listener for the click event
google.maps.event.addListener(map, 'click', addLatLng);
}////Function initialize ends here
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
/**
* Handles click events on a map, and adds a new point to the Polyline.
* #param {google.maps.MouseEvent} event
*/
function addLatLng(event) {
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
markersArray.push(marker);
}///Function addLatLng ends here
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
}
function clearall() {
poly.setMap(null);//Just hiding them
clearMarkers();
markersArray = [];
///////////////////CLEAR ALL VALUES IN HERE i.e. miles, time etc and CLEAR MARKERS
restartpolyline();
}
//////////////////////////////////////////WHEN CLEARED THE CODE NEEDS INTITALISING AGAIN
function restartpolyline(){
//alert("Restart");
}
//https://developers.google.com/maps/documentation/javascript/reference#Polyline
google.maps.event.addDomListener(window, 'load', initialize);
To view what currently happens view the following link: http://kitlocker.com/sotest.php
Instead of poly.setMap(null); call path.clear();
Polyline is just an array of LatLng objects, not individual Polylines, which you can then loop over to remove them all.
You can make it invisible or remove it from the map by looping it like this:
var size = poly.length;
for (i=0; i<size; i++)
{
poly[i].setMap(null);
}

How To get all latitude and longitude from source to destination place on selection of suggested routes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i want to fetch all the latitude and longitude between origin place to destination place.
For that i have written following script but it will not give me the latitude and longitude between those two place.
<script type="text/javascript">
var directionDisplay;
var directionsRenderer;
var directionsService = new google.maps.DirectionsService();
var map;
function drawMap(midpoint) {
var mid = midpoint.split(",");
var start = new google.maps.LatLng(mid[0], mid[1]);
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: start,
mapTypeControl: false
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var input = (document.getElementById('origin'));
var inputdestination = (document.getElementById('destination'));
var types = document.getElementById('changetype-all');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var autocompletedestination = new google.maps.places.Autocomplete(inputdestination);
autocompletedestination.bindTo('bounds', map);
}
function getRendererOptions(main_route) {
if (main_route) {
var _colour = '#00458E';
var _strokeWeight = 4;
var _strokeOpacity = 1.0;
var _suppressMarkers = false;
}
else {
var _colour = '#ED1C24';
var _strokeWeight = 2;
var _strokeOpacity = 0.7;
var _suppressMarkers = false;
}
var polylineOptions = { strokeColor: _colour, strokeWeight: _strokeWeight, strokeOpacity: _strokeOpacity };
var rendererOptions = { draggable: true, suppressMarkers: _suppressMarkers, polylineOptions: polylineOptions };
return rendererOptions;
}
function renderDirections(result, rendererOptions, routeToDisplay) {
if (routeToDisplay == 0) {
var _colour = '#00458E';
var _strokeWeight = 4;
var _strokeOpacity = 1.0;
var _suppressMarkers = false;
}
else {
var _colour = '#ED1C24';
var _strokeWeight = 4;
var _strokeOpacity = 0.7;
var _suppressMarkers = false;
}
// if (routeToDisplay == 0) _colour = "#FF0000";
// create new renderer object
var directionsRenderer = new google.maps.DirectionsRenderer({
draggable: true,
suppressMarkers: _suppressMarkers,
polylineOptions: {
strokeColor: _colour,
strokeWeight: _strokeWeight,
strokeOpacity: _strokeOpacity
}
});
directionsRenderer.setMap(map);
directionsRenderer.setPanel(document.getElementById('directions_panel'));
directionsRenderer.setDirections(result);
directionsRenderer.setRouteIndex(routeToDisplay);
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
Below if condition is used for get all latitude and longitude between two places but it is not wokrs.
if (response.routes && response.routes.length > 0) {
var routes = response.routes;
for (var j = 0; j < routes.length; j++) {
var points = routes[j].overview_path;
var ul = document.getElementById("vertex");
for (var i = 0; i < points.length; i++) {
var li = document.createElement('li');
li.innerHTML = getLiText(points[i]);
ul.appendChild(li);
}
}
}
}
});
}
function getLiText(point) {
var lat = point.lat(),
lng = point.lng();
return "lat: " + lat + " lng: " + lng;
}
function requestDirections(start, end, routeToDisplay, main_route) {
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
provideRouteAlternatives: main_route
};
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
if (main_route) {
var rendererOptions = getRendererOptions(true);
for (var i = 0; i < result.routes.length; i++) {
renderDirections(result, rendererOptions, i);
}
}
else {
var rendererOptions = getRendererOptions(false);
renderDirections(result, rendererOptions, routeToDisplay);
}
}
});
}
</script>
Below is the body:
<body>
<div id="vertex-container">
<label>Points</label>
<ul id="vertex">
</ul>
</div>
<div>
//...all the other input and button
//....
</body>
From above script i can get all the route from origin place to destination place but i didnt get the all latitude and longitude between those place.
you can see that i can get suggested route between two place.
But now i want to print all latitude and longitude between those route which i am selecting.
Suppose here 3 routes are there .
now suppose i am selecting 1st then it will fetch all the latitude and longitude between those places only for that route
Now suppose i am slecting 2nd suggested route then it will display all latitude and longitude between that route
so now ,
how can i get all the latitude and longitude between those places for selected route from suggested routes?
You have to loop through the alternate routes and for each route loop through all steps.
Here is an example that shows how to draw all the alternate routes to the map and place a marker at each step. I have used different colors so you can clearly identify each route.
Note that it uses the start_location of each step. We don't know if that is what you need.
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var center = new google.maps.LatLng(0, 0);
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
}
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
directionsDisplay.setMap(map);
var start = "Yamuna Nagar, Haryana, India";
var end = "New Delhi, India";
var method = 'DRIVING';
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode[method],
provideRouteAlternatives: true
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var routesSteps = [];
var routes = response.routes;
var colors = ['red', 'green', 'blue', 'orange', 'yellow', 'black'];
for (var i = 0; i < routes.length; i++) {
new google.maps.DirectionsRenderer({
map: map,
directions: response,
routeIndex: i,
polylineOptions: {
strokeColor: colors[i],
strokeWeight: 4,
strokeOpacity: .3
}
});
var steps = routes[i].legs[0].steps;
var stepsCoords = [];
for (var j = 0; j < steps.length; j++) {
stepsCoords[j] = new google.maps.LatLng(steps[j].start_location.lat(), steps[j].start_location.lng());
new google.maps.Marker({
position: stepsCoords[j],
map: map,
icon: {
path: 'M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0',
scale: .5,
fillColor: colors[i],
fillOpacity: .3,
strokeWeight: 0
},
title: steps[j].maneuver
});
}
routesSteps[i] = stepsCoords;
}
// Here is your array of routes steps coordinates
console.log('routesSteps', routesSteps);
}
});
}
initialize();
JSFiddle demo

Categories

Resources