Is possible to add waypoints to Google Maps API without using JSON? - javascript

I'm on ASP.NET MVC and I'm using Google Maps API with Javascript. I send a Model to the View with one or more waypoints to add to the route.
function calcRoute() {
initialize();
var start = "<%= Model.StartAddress %>";
var end = "<%= Model.ClientAddress %>";
var waypts = [];
waypts.push({
location: "<%= Model.PickupAddress[0] %>",
stopover:true
});
var request = {
origin: start,
destination: end,
waypoints: waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Is it possible to add waypoints this way with the addresses in Model.PickupAddress array? I have seen examples code by using JSON (for markers), but if I can do it directly in this Javascript code, that's fine for me.

Related

Google Maps API asynchronous

I'm currently working with the Google Maps API. I use the globalFunction when user click on some button. The "calcRoad" function generate the road by using the Google Maps API, and then "Myfunction" use the data from "calcRoad" to do some calculation.
My problem is that right now "Myfunction" doesn't wait "calcRoad" to end before starting. I asume that some of the Google API requests are asynchronous but I can't access the code behind it.
How could I forced "Myfunction" to wait until "calcRoad" is done ?
function globalFunction(){
calcRoad(true,latitude, longitude);
Myfunction();
}
function calcRoad(bool,lat,long) {
marker.setVisible(false);
var date = new Date();
// Add a waypoint
if(bool){
var tampon = new google.maps.LatLng(lat,long);
waypoints.push({
location: tampon,
stopover:false
});
}
var request = {
origin: departure_place.geometry.location,
destination: arrival_place.geometry.location,
travelMode: google.maps.TravelMode[mode],
waypoints: waypoints,
avoidHighways: false,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
PS: I tried to use some setTimeout before calling "Myfunction" and it is working but as I don't know how long will the "calcRoad" take to finish (depending on users' parametres) I can't use setTimeout.
I hope that I'm clear with my probleme, thanks in advance for your help.
You should add a callback parameter in your calcRoad function :
function globalFunction(){
calcRoad(true,latitude, longitude, Myfunction);
}
function calcRoad(bool,lat,long, cb) {
marker.setVisible(false);
var date = new Date();
// Add a waypoint
if(bool){
var tampon = new google.maps.LatLng(lat,long);
waypoints.push({
location: tampon,
stopover:false
});
}
var request = {
origin: departure_place.geometry.location,
destination: arrival_place.geometry.location,
travelMode: google.maps.TravelMode[mode],
waypoints: waypoints,
avoidHighways: false,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
cb && cb(); // Check if "cb" callback function is defined and execute it
}
});
}
Something like this should work !

Google Maps API Intel XDK Waypoints

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.

Google Maps API: ZERO RESULTS or INVALID REQUEST while drawing routes

I am trying to draw a route based on the co-ordinates that i receive from the database. But somehow i am not able to draw. I either get ZERO RESULTS or INVALID REQUEST.. The route i am trying to draw is a TRANSIT ROUTE. Where as i found some similar issues(Link) being addressed in the site but the solution given was to add departure time or arrival time in the parameters. And it was an accepted answer. The same which i tried is not working currently. I have posted the code that i have tried.
Below are the co-ordinates:
19.1860640243063 72.9759523272514
19.1902699 73.023094
19.2178474133021 73.086293040406
19.2354157727173 73.1302742969937
Please help.
load : function(response)
{
for(var i=0;i<response.length;i++)
{
if(response[i].linkData!='undefined')
{
link=response[i].linkData;
var lastPos=(response.length-1);
linkDes=response[lastPos].linkData;
var linkDes=link.split(" ");
var linkValue=link.split(" ");
var latDes= parseFloat(linkDes[0]);
var longDes= parseFloat(linkDes[1]);
var lat = parseFloat(linkValue[0]); //convert string to float
var lon = parseFloat(linkValue[1]); //convert string to float
if(count==0)
{
var source=new google.maps.LatLng(lat, lon);
count++;
}
if(i!=0 )
{
geoLatLong=new google.maps.LatLng(lat, lon);
count++;
}
if(i!=response.length-1)
{
geoLatLong=new google.maps.LatLng(lat, lon);
}
if(latDes!="" && longDes!="")
{
var destination=new google.maps.LatLng(latDes, longDes);
}
if(count>1 && count<=response.length-1)
{
geoLatLongArray.push(geoLatLong);
}
}
}
for(var i=0;i<geoLatLongArray.length;i++)
{
waypts.push({location:geoLatLongArray[i],stopover:true});
}
var request = {
origin: source,
destination: destination,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.TRANSIT,
transitOptions:
{
departureTime: new Date()
}
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
alert("directions response "+status);
}
});
}
According to v3 API Docs
google.maps.TravelMode.TRANSIT
is the correct syntax.
I had similar issue. I fixed it after making origin to an address field (instead of coordinates). this issue persists only when both origin and destination are coordinates.
You can perhaps convert your coordinates into address using Reverse Geocode API and then pass the converted addresses to origin / destination.

Google Maps Api check if place is on the route

I made with Google Maps an route between two places. Thats works fine.
But i also have an database with interesting points on different roads in
my country. I like to show them if they are on the generated route. Places who are
not one this route, don't need to be shown.
My database with intereseting points contains latitude and longitude coordinates.
How can i check is they are on my route? There are approximately 30 or 40 interesting
point in my database.
// set request
var request = {
origin: initialLocation,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
// make route
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// set route
directionsDisplay.setDirections(response);
}
});
UPDATE:
Build new function "isLocationOnEdge". But the check runs the markers when they are not on the road:
// get flitsers on the route
function getFlitsersOnRoute(){
// set request
var request = {
origin: current_location,
destination: $('#gegevens').html(),
travelMode: google.maps.TravelMode.DRIVING
};
// make route
directionsService.route(request, function(response, status) {
// isLocationOnEdge
var isLocationOnEdge = google.maps.geometry.poly.isLocationOnEdge;
var coords = response.routes[0].overview_path;
var image = base_url+'external/afbeeldingen/google_markers/flitser.png';
// get flitsers
$.ajax({
type: "POST",
async:false,
url: base_url+"advies/get/9",
success: function (data) {
var result = jQuery.parseJSON(data);
// loop trough flitsers
$.each(result.flitsers.m, function(i, item) {
// latitude longitude
var latlng = item["#attributes"].gps.split(",");
// make google latlng
var myLatlng = new google.maps.LatLng(latlng[0],latlng[1]);
if (myLatlng,coords)
{
// set and define the marker
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
size: new google.maps.Size(15, 15),
icon: image,
title: 'Flitser'
});
}
});
}
});
});
}
isLocationOnEdge(point:LatLng, poly:Polygon|Polyline, tolerance?:number)
To determine whether a point falls on or near a polyline, or on or near the edge of a polygon, pass the point, the polyline/polygon, and optionally a tolerance value in degrees to google.maps.geometry.poly.isLocationOnEdge(). The function returns true if the distance between the point and the closest point on the line or edge falls within the specified tolerance. The default tolerance value is 10-9 degrees.
https://developers.google.com/maps/documentation/javascript/geometry
Include the geometry library in your Google Maps API request:
http://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry&sensor=TRUE_OR_FALSE
Pseudo-code:
// Make isLocationOnEdge easier to access
var isLocationOnEdge = google.maps.geometry.poly.isLocationOnEdge;
for (var i = 0; i < interestingPlaces.length; i++) {
if (isLocationOnEdge(interestingPlaces[i],
response.routes[0].overview_path))
{
// Do something with interestingPlaces[i]
}
}
Google maps documentation for isLocationOnEdge()

Using waypoints to find the route

I am working on finding the route between two points using javascript, google maps api v3 and pgoruting. Now I have the following method which works fine when I give just one waypoint. BUT it does not work when I jave more than one waypoint. The format when there is more than one waypoint is delimeted with this symbol '|'. Therefore for example: 36.762121,14.7866553|35.988777778,14.655444333
The javascript method is the following:
function calcRoute() {
var all_nodes = document.getElementById('result').innerHTML;
var node = all_nodes.split("|");
var start = node[0];
var end = node[node.length - 1];
var wpts = [];
for (var i = 1; i < node.length-1; i++) {
wpts.push({
location:node[i],
stopover:true
});
}
var request = {
origin: start,
destination: end,
waypoints: wpts,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
alert('No route found');
}
});
}
Actual thats incorrect waypoints are arrays of location:LatLng and stopover:true or false and they do not use the pipe delimiter please refer to Waypoints
As previously suggested, it might help to get a google object for the location and it may also help to supply the lat and long as two seperate entities.
for (var i = 1; i < node.length-1; i = i + 1) {
node[i] = node[i].split(',');
wpts.push({
location:new google.maps.LatLng(node[i][0], node[i][1]),
stopover:true
});
}

Categories