Google Maps API Intel XDK Waypoints - javascript

For a school project I have to make an app, using Intel XDK, jQuery Mobile and an API. I wanted to make an app in which you can make a route and display this route on a google-maps-map (like a travelapp to view your trips).
I used Intel XDK (HTML5 + Cordova and the App Designer) and got an API key from the Google Maps Javascript API.
Right now, I have used the Google Maps API and displaying a route from A to B went well. In the following code (this is in my script) I tried to add waypoints to my route. In my HTML code I have three text-inputs for the user (start, via (=waypoint), end), the map and a button to show the route. I have looked at many sample codes, but my code doesn't work and I don't know why. There is no error, but if you push the showbutton, nothing happens. What have I done wrong or what did I miss?
I hope anyone can help and thanks in advance!
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initMap() {
var latlng = new google.maps.LatLng(41.850033, -87.6500523);
// set direction render options
//var rendererOptions = { draggable: true };
directionsDisplay = new google.maps.DirectionsRenderer({map: map});
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
// add the map to the map placeholder
var map = new google.maps.Map(document.getElementById("gmap"),myOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = $('#start-input').val();
var via = $('#via-input').val();
var end = $('#end-input').val();
var waypts = [];
waypts.push({
location: via,
stopover: true
});
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
unitSystem: google.maps.UnitSystem.IMPERIAL,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
alert('Directions request failed due to ' + status);
}
});
}
function createMarker(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
}
/* button #show-btn */
$(document).on("click", "#show-btn", function(evt) {
initMap();
createMarker(start);
createMarker(via);
createMarker(end);
return false;
});

You're creating the variables start, via and end as local variables in your calcRoute function, meaning they're not available to any code outside of that function. So when you try and refer to them in these lines, they'll be undefined, and I suspect you're getting a JS error:
createMarker(start);
createMarker(via);
createMarker(end);
Make them global variables instead; define them at the same time as you do this:
var directionDisplay;
i.e. that becomes:
var directionDisplay, start, via, end;
And then remove the var keyword from where you refer to them in the calcRoute function, i.e. do:
function calcRoute() {
start = $('#start-input').val();
via = $('#via-input').val();
end = $('#end-input').val();
You also have the same problem with your map variable. You create that as a local variable in your initMap function, and then try and refer to it in the createMarker function, which won't have access to it. Make that a global variable too.

Related

Google Direction Service - Route from current location to defined destination [duplicate]

This question already has an answer here:
Get directions to predefined destination from current location (Geolocation)
(1 answer)
Closed 5 years ago.
This is my script which currently displays a route for either car or transit depending on what the user has selected.
Would anyone know how to adapt this script to set the origin as the users current location and route from that to set lat + long destination.
As I have currently been unable to find a way to integrate this within my script - any help would be much appreciated!
function initMap() {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {lat: *VALUE*, lng: *VALUE*}
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('right-panel'));
calculateAndDisplayRoute(directionsService, directionsDisplay);
document.getElementById('mode').addEventListener('change', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var selectedMode = document.getElementById('mode').value;
directionsService.route({
origin: {lat: *VALUE*, lng: *VALUE*}, // Haight.
destination: {lat: *VALUE*,lng: *VALUE*}, // Ocean Beach.
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode],
transitOptions: {
arrivalTime: new Date(1489242600000),
routingPreference: 'FEWER_TRANSFERS'
},
unitSystem: google.maps.UnitSystem.IMPERIAL,
provideRouteAlternatives: true
}, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
In the google directions API you can read what parameters you can add. In your case you would need origin and destination and maybe waypoints if you are planning to make a route with multiple stops.
https://developers.google.com/maps/documentation/directions/intro#Waypoints
In the link below there is an example how you can select multiple way points. For the location you can use Geolocation to get the latitude and longitude. Those can be implemented in the calculateAndDisplay function in the origin parameter.
directionsService.route({
origin: //here you can put lat/long or a name
destination: //here you can put lat/long or a name
waypoints: // waypoints expect an Array of locations or lat/long
optimizeWaypoints: true,
travelMode: 'DRIVING'
},
https://developers.google.com/maps/documentation/javascript/examples/directions-waypoints

Google Maps Api - Passing google.maps.Place to Direction Service

According to the Google documnetation, one can pass the Google Place ID of a location to the Direciton Service. However, regardless of what combination I try, I absolutely cannot get it to work; I am receiving a NOT_FOUND error. I have tried hard coding the id as a test to no avail.
The basic initialization code:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var hotelMap;
var placesService;
function initialize() {
var mapOptions = {
center: { lat: 37.30138, lng: -89.57778},
zoom: 15,
};
hotelMap = new google.maps.Map(document.getElementById("googlemaps"), mapOptions);
var marker = new google.maps.Marker({
position:{ lat: 37.30138, lng: -89.57778},
map: hotelMap,
});
var info = new google.maps.InfoWindow({
content: "3265 William Street, Cape Girardeau, MO 63701"
});
marker.setMap(hotelMap);
info.open(hotelMap, marker);
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(hotelMap);
directionsDisplay.setPanel(document.getElementById("directionModalBody"));
document.getElementById("searchButton").addEventListener("click", function() {
var keyword = document.getElementById("searchBox").value;
var requestOptions = {
location: { lat: 37.3011339, lng: -89.5770238},
radius: '5000',
keyword: keyword
};
placesService = new google.maps.places.PlacesService(hotelMap);
placesService.nearbySearch(requestOptions, findCallback);
});
}; // end initiallize
The window.onload function:
window.onload = function() {
initialize();
document.getElementById("calcDirections").onclick = function() {
if ($("#city").val() != null && $("#city").val() != "") {
findRoute();
} else {
alert("Please Enter a City");
}
}; // end onclick
$(".areaList").on("click", "a", function(e) {
e.preventDefault();
var placeID = $(this).attr("href");
locationRoute(placeID);
}) // end onclick
};
The problem function:
function locationRoute(locationID) {
var start = "ChIJfbJ8AyaId4gR4XCrciru2Qc";
var end = new google.maps.Place(locationID);
alert(locationID);
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
}; // end request object
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
document.getElementById("getDirectionButton").click();
} else {
alert(status);
}// end if
}); // end route
} // end findRoute
I have tried just passing the place IDs as a string with no success. I have tried prefixing them, again no success. It seems from the Google documentation, one needs to create a google.maps.Place object, but how? I consulted the documentation (https://developers.google.com/android/reference/com/google/android/gms/location/places/Place#getId()), but did not see a constructor. How can I resolve this issue? Thanks so much.
Try this
directionsService.route({
origin: {placeId: start},
destination: {placeId: locationID}
...
There are two different options available
if you want to use place id
directionsService.route({
origin: {placeId: start},
destination: {placeId: locationID})
if you want to use lat and long
directionsService.route({
origin: {location: {lat:33.699234,lng:-102.870486}},
destination: {location: {lat:33.123366,lng:-102.862864}},
travelMode: "DRIVING"
and also make sure you configure direction service in google console
here is the link for that
https://developers.google.com/maps/documentation/javascript/directions

How to read polyline lat/long from directions?

I am trying to convert my v2 Google Maps code to v3 and I'm having problems getting the polyline from directions. Basically I am trying to get the lat/long all along the path at specific interval (every 100 miles or so). In the past I used getPolyline and getVertexCount. I would then divide the VertexCount by number of miles and get an approximate number in the polyline that I should be looking at. I know with v3 both of those commands are gone. I've used the below code to get the polyline but I'm unsure that I'm getting anything because when I run an alert I get [object Object].
var map;
var gdir;
var poly;
var tempstr;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
var rendererOptions = {
draggable: true
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(37.0, -107.0)
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions'));
poly = new google.maps.Polyline;
setDirections("Colorado Springs", "Phoenix");
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
var thispathlatlong;
thispathlatlong = poly.getPath();
alert(thispathlatlong);
});
}
function setDirections(fromAddress, toAddress) {
tempstr = {
origin:fromAddress,
destination:toAddress,
provideRouteAlternatives: false,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
};
directionsService.route(tempstr, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
It draws the directions but I can't get the lat long from the array. I know it's now in a MVCarray but I don't know how to use that. I can't read it.
This is my site http://www.orbitalspeeds.com/
To be specific, I am trying to get the directions polyline that Google creates when plotting a route. Most of the help I've found is about making a polyline; I want to grab the one that Google Maps creates and parse the lat/longs into an javascript array that I can use later.
Thanks for any help.

Resetting Center of Map in Google Maps through Javascript

I have an MVC application that is using Google Maps throughout the app. To make things simple, I've created a JavaScript file that initializes the map and sets the map display.
In my application, I want to allow a front end developer to change the center of the map location with a simple JavaScript call. Unfortunately, after declaring the map and loading the application, if you try to make a JavaScript call back to the map variable, the map JS variable (and all variables) are null. This drops the instance to the map, and does not let me change the location (I believe).
In the JS Code below, I'm trying to call setLocation from the HTML page to reset the location. This is the fail part of the code. Help is appreciated.
var map;
var geocoder;
var marker;
$(document).ready(function () {
initialize();
$(function () {
$("#address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function (request, response) {
geocoder.geocode({ 'address': request.term }, function (results, status) {
response($.map(results, function (item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
select: function (event, ui) {
$("#Place_Latitude").val(ui.item.latitude);
$("#Place_Longitude").val(ui.item.longitude);
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
marker.setPosition(location);
map.setCenter(location);
}
});
});
});
function setLocation(lat, lon) {
var location = new google.maps.LatLng(lat, lon);
marker.setPosition(location);
map.setCenter(location);
}
function initialize() {
var location = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
center: location, zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
marker = new google.maps.Marker({
map: map,
draggable: true
});
marker.setPosition(location);
geocoder = new google.maps.Geocoder();
}
This looks bad:
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
The geocoder is asynchronous and can't return anything from the callback routine. you need to use the variables inside the callback.
There is an example of what you are trying to do here...
Have a look at theie placeMarker function and how they have initialized the map...
My suggestion would be to start with this example and make sure that works. If so, it should be relatively straight forward to determine what is different in your implementation.

Google Maps API v3 custom markers not appearing

I want to display on my website something similar to google maps transit directions, so I am trying to display multiple different types of directions on the same map. For exmaple, I want to show a trip where you walk to the bus, take the bus to some other street, and then walk to your final destination.
To do this, I am trying to get the result of multiple directions requests on the same map with custom markers. I have a function called change_map(), which is supposed to display the information for one of these trips on the map.
I have 2 problems:
the markers do not show up on the map.
when fitbounds is un-commented, I get a stack limit exceeded error
I am new to javascript, sorry if my code sucks and thanks for your help!
var trip_map
function renderDirections(result) {
var directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(trip_map);
directionsDisplay.suppressMarkers = true;
directionsDisplay.setDirections(result);
}
function requestDirections(start, end) {
var directionsService = new google.maps.DirectionsService;
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result) {
renderDirections(result);
});
}
function change_map(pk) {
var myOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
trip_map = new google.maps.Map(document.getElementById("trip_map"),
myOptions);
var bounds = new google.maps.LatLngBounds();
for (var j = 0; j < latlngpairs.length; j++) {
var GPS = new google.maps.LatLng({lat:latlngpairs[0],
lng:latlngpairs[1]});
var end_marker = new google.maps.Marker({position: GPS,
map: trip_map,
title: "Hello World!"});
bounds.extend(end_GPS);
}
requestDirections(parts[j], parts[j+1]);
}
//trip_map.fitBounds(bounds);
}
I believe the problem is that you are passing a single object as argument to the constructor of LatLng inside the loop
Change
var GPS = new google.maps.LatLng({lat:latlngpairs[0],lng:latlngpairs[1]});
with
var GPS = new google.maps.LatLng(latlngpairs[0],latlngpairs[1]);
Hope that solves it.

Categories