DirectionsService not working as required by the code - google-maps

I am trying to make routes between any 2 locations I pass using DirectionsService of google maps. The locations are coming to me dynamically. But the problem I am facing is when the next 2 coordinates come it removes the previous route and displays the new route with the new coordinaates. I also can't use the waypoints because max. 8 waypoints are allowed and I need more than that.
here is my code:
var marker;
var map;
var mapOptions;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
function initialize() {
var rendererOptions = {
map : map,
suppressMarkers : true
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
mapOptions = {
zoom: 12,
center: new google.maps.LatLng(23.53265,77.754812)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
directionsDisplay.setMap(map);
}
//var image = 'C:\Users\Samir\Desktop\download.jpg';
var start = new google.maps.LatLng(23.32654,77.32685);
function Plot_Data(latlng){
//end = new google.maps.LatLng(lat,lng);
marker = new google.maps.Marker({
position: latlng ,
map: map
});
var request = {
origin:start,
destination:latlng,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
start = latlng;
}

A directionsRenderer will display only one route at a time. This will add a new one for each time you call the Plot_Data function, but will still be subject to the API rate and query limits:
var marker;
var map;
var mapOptions;
var directionsDisplay = [];
var directionsService = new google.maps.DirectionsService();
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
function initialize() {
var rendererOptions = {
map : map,
suppressMarkers : true
}
directionsDisplay.push(new google.maps.DirectionsRenderer(rendererOptions));
mapOptions = {
zoom: 12,
center: new google.maps.LatLng(23.53265,77.754812)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
directionsDisplay.setMap(map);
}
//var image = 'C:\Users\Samir\Desktop\download.jpg';
var start = new google.maps.LatLng(23.32654,77.32685);
function Plot_Data(latlng){
//end = new google.maps.LatLng(lat,lng);
marker = new google.maps.Marker({
position: latlng ,
map: map
});
var request = {
origin:start,
destination:latlng,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay[directionsDisplay.length-1].setDirections(response);
directionsDisplay[directionsDisplay.length-1].setMap(map);
directionsDisplay.push(new google.maps.DirectionsRenderer(rendererOptions));
} else alert("directions request failed: " +status);
});
start = latlng;
}

Related

The direction does not show my current location and the destination

See this image.
I try to show my current location to the destination but the direction does not show up in the map, it just show the route at panel only.
navigator.geolocation.getCurrentPosition(function (position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var coords = new google.maps.LatLng(latitude, longitude);
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
var trafficLayer = new google.maps.TrafficLayer();
var mapOptions =
{
zoom: 15,
center: coords
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
displayRoute(directionsService, directionsDisplay);
function displayRoute(service, display) {
service.route({
origin: coords,
destination: new google.maps.LatLng(5.409722, 100.313319),
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
});
The map does not show the direction from my current location to destination.
When you create your google.maps.DirectionsRenderer, the map is undefined. Either create the google.maps.DirectionsRenderer after the map, or call .setMap on it once the map is defined.
var coords = new google.maps.LatLng(latitude, longitude);
var directionsService = new google.maps.DirectionsService;
var trafficLayer = new google.maps.TrafficLayer();
var mapOptions = {
zoom: 15,
center: coords
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
displayRoute(directionsService, directionsDisplay);
proof of concept fiddle
code snippet:
var geocoder;
var map;
// [ 0 ]: Tapah, Perak, Malaysia (4.19773, 101.261529)
function initialize() {
var latitude = 4.19773;
var longitude = 101.261529;
var coords = new google.maps.LatLng(latitude, longitude);
var directionsService = new google.maps.DirectionsService;
var trafficLayer = new google.maps.TrafficLayer();
var mapOptions = {
zoom: 15,
center: coords
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
displayRoute(directionsService, directionsDisplay);
function displayRoute(service, display) {
service.route({
origin: coords,
destination: new google.maps.LatLng(5.409722, 100.313319),
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
<div id="right-panel"></div>

Pass Google Maps SearchBox result to Directions Service

After reading documentation for the SearchBox class, the Places library including the AutoComplete class, and the Directions service, I cannot figure out how to pass the address selected by a user from the SearchBox to the Directions service to draw the map. The map and marker display correctly, and the SearchBox displays and functions correctly. On the "place_change" event, though, nothing happens. My code:
var rawlatitude = <?php echo $loc_lat; ?>;
var rawlongitude = <?php echo $loc_long; ?>;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude,longitude);
google.maps.event.addDomListener(window, 'load',initMap(latitude,longitude));
function initMap(lat,lng) {
// instantiate directions service object
var directionsService = new google.maps.DirectionsService;
// create map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: latlong
});
// add marker
var marker = new google.maps.Marker({
position: latlong,
map: map
});
// put address search box into map
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// create directions renderer and bind it to map
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
// listen to and respond to address search
var onChangeHandler = function() {
var location = searchBox.getPlaces();
var start = location.place_id;
calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
};
google.maps.event.addListener(searchBox, 'place_change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
directionsService.route({
origin: start,
destination: latlong,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if(status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
As Dr.Molle observed in his comment,
There is no place_changed-event for a SearchBox, it's an event for Autocomplete. The event for a SearchBox is called places_changed.
Also note that a SearchBox.getPlaces() returns an array with places
working fiddle
working code snippet:
var rawlatitude = 40.7127837;
var rawlongitude = -74.0059413;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude, longitude);
var viewport = {
"south": 40.4960439,
"west": -74.2557349,
"north": 40.91525559999999,
"east": -73.7002721
};
google.maps.event.addDomListener(window, 'load', function() {
initMap(40.735657, -74.1723667);
});
function initMap(lat, lng) {
// instantiate directions service object
var directionsService = new google.maps.DirectionsService;
// create map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: latlong
});
// add marker
var marker = new google.maps.Marker({
position: latlong,
draggable: true,
map: map
});
// put address search box into map
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: viewport
});
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// create directions renderer and bind it to map
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
// listen to and respond to address search
var onChangeHandler = function() {
var locations = searchBox.getPlaces();
var start = locations[0].place_id;
var bounds = new google.maps.LatLngBounds();
bounds.extend(latlong);
bounds.extend(locations[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
position: locations[0].geometry.location,
map: map,
title: locations[0].name
})
calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
};
google.maps.event.addListener(searchBox, 'places_changed', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
directionsService.route({
origin: {
placeId: start
},
destination: {
location: latlong
},
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="pac-input" />
<div id="map"></div>

IBM Worklight 6.0 - Google maps fail to load while retrieving directions

I am using Google API v3 for "directions to here". However, the maps are not getting loaded properly. I am getting no error in logs.
When the page loads, I do the following:
var startPoint = new google.maps.LatLng(start.lat(), start.lng());
var endPoint = new google.maps.LatLng(parseFloat(end.latitude), parseFloat(end.longitude));
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 15,
mapTypeControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
center: endPoint
};
var map = new google.maps.Map(document.getElementById("branchLocatorSiteMapCanvas"), mapOptions);
$r.currentPage.map = map;
$page.off('pageshow').on('pageshow', function () {
// Suitable for V3 and fix for map div is not rendered
if ($r.currentPage.map) {
var timer = window.setTimeout(function () {
google.maps.event.trigger($r.currentPage.map, 'resize');
if (endPoint) {
$r.currentPage.map.setCenter(endPoint);
}
else if (startPoint) {
$r.currentPage.map.setCenter(startPoint);
}
window.clearTimeout(timer);
}, 400);
}
});
if ($r.currentPage.map) {
google.maps.event.addListenerOnce($r.currentPage.map, 'idle', function () {
// Do something only the first time the map is loaded
google.maps.event.trigger($r.currentPage.map, 'resize');
$r.currentPage.map.setCenter(endPoint);
});
I use this snippet for Direction Service and Rendering.
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
I didn't try it with your code example, but you can take this simpler demo project to see how to make it work in a Worklight 6.0.0.2-based app: Google Maps Directions Demo project.
The demo project is based on this example via the Google Maps documentation.
End result is:
JavaScript portion of the app:
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
var map;
function wlCommonInit(){
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 7,
disableDefaultUI: false,
center: chicago
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
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);
}
});
}

How to get city name from parameter variable for Google Map API

I am using this function: getDirection(glat,glon,acity) Using this function I have to draw a route from a city to the glat and glong [latitude and longitude] position. I was finished with everything but I dont know how to set variable acity as origin.
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var default_latitude=22.5936840;//12.9715987;
var default_longitude=78.962880;//77.5945627;
var myOptions =
{
center: new google.maps.LatLng(default_latitude,default_longitude),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapp"),myOptions);
var latlng=new google.maps.LatLng(glat,glon);
$('#mapDiv1').modal({closeClass: "mapCloseImg1"});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("panel"));
var request = {
origin: [WANT TO PUT ACITY AS ORIGIN BUT DONT KNOW HOW]
destination:latlng,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}

Google Maps Waypoints not showing up

I am new to the Google Maps API and so far I have run into many issues.
I am trying to map waypoints from latlng coords determined by an array of checkboxes.
Here is my js file in full:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var waypts = [];
var start = new google.maps.LatLng(41.850033, -87.6500523);
var end = new google.maps.LatLng(40.850033, -87.6500523);
function initialize()
{
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
function calcRoute()
{
var checkboxArray = document.getElementsByName("waypoints[]");
for (var i = 0; i < checkboxArray.length; i++)
{
if (checkboxArray[i].checked)
{
var lat = parseFloat(checkboxArray[i].attributes["lat"].value);
var lng = parseFloat(checkboxArray[i].attributes["lng"].value);
waypts.push({
location: new google.maps.LatLng(lat, lng),
stopover: true
});
}
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
console.log("mapping...");
if(status == google.maps.DirectionsStatus.NOT_FOUND)
{
console.log("Could not one or more of locations");
}
});
The map shows up and "mappings..." pops in the console when the page loads. When I press the calcRoute submit button nothing happens. I have logged the lat/long and the waypt object so I know they are getting to that point but it seems the route is never recalculated, etc.
I really just need a basic demo on this but the only one I have found is which I have used for almost everything but I get no results:
Google Example Directions Waypoints
Currently your script never will show any route, because you are missing the call of directionsDisplay.setDirections() to print the route.
You also should should put the call of directionsService.route() into the calcRoute-function.
fixed code:
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var start = new google.maps.LatLng(41.850033, -87.6500523);
var end = new google.maps.LatLng(40.850033, -87.6500523);
function initialize()
{
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
function calcRoute()
{
var checkboxArray = document.getElementsByName("waypoints[]");
var waypoints=[];
for (var i = 0; i < checkboxArray.length; i++)
{
if (checkboxArray[i].checked)
{
var lat = parseFloat(checkboxArray[i].attributes["lat"].value);
var lng = parseFloat(checkboxArray[i].attributes["lng"].value);
waypts.push({
location: new google.maps.LatLng(lat, lng),
stopover: true
});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if(status == google.maps.DirectionsStatus.OK)
{
//print the route
directionsDisplay.setDirections(response);
}
else
{
console.log('something went wrong',status);
}
});
}
</script>
There isn't a great deal of information about how your Javascript relates to the page HTML. But this line
var checkboxArray = document.getElementsByName("waypoints[]");
should probably be
var checkboxArray = document.getElementsByName("waypoints");
assuming that all your checkboxes have the name waypoints.
What is inside the quotes should exactly match the name of the checkbox elements, so if each checkbox has the name waypoint (because each checkbox marks a single waypoint, this is a possibility) then you should use .getElementsByName("waypoint") to find all elements which have that name.