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()
Related
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.
I have a program that allows the user to select multiple items for a trip. Part of the program maps the items in google maps. I am using the lat/long coordinates to generate the waypoints and then the API takes it from there. The final map shows the route and markers. I would like to give each marker a custom name instead of the default street address currently being displayed. Is this possible?
//Display the route on the map
$.post("processors/getMapWayPoints.php",{
tripID: tripID
}, function(e){
console.log("Return is " + e);
latlong = JSON.parse(e);
//iterate through each locations lat/long and add it to the mappoints array for the route plotting
for(var i = 0; i < latlong.length; i+=3){
var name = latlong[i];
var lat = latlong[i+1];
var lng = latlong[i+2];
//create google lat/long point object
var pt = new google.maps.LatLng(lat, lng);
//add the location to the array for the route
mappoints.push({location:pt, stopover:true});
//not being used yet
pointNames.push(name);
}
var mapOptions = {
zoom:11,
center: home
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
var request = {
origin:home,
destination:home,
waypoints: mappoints,
//optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
});
I'm doing my work with Google Map API. To draw a route between two points, I use this function:
function calcRoute(start, end) {
var pStart = new google.maps.LatLng(start.lat(), start.lng());
var pEnd = new google.maps.LatLng(end.lat(), end.lng());
var request = {
origin: pStart,
destination: pEnd,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
// Box the overview path of the first route
var path = result.routes[0].overview_path;
boxes = rboxer.box(path, distance);
//drawBoxes(boxes);
nearbyMarkets = search_market(boxes);
// PUT HERE???
}
});
}
After this, I need access the Direction Display object, which only available after the route is rendered successfully (means this function's done). I tried to put that code block in that position, but at that time, the Direction property of Direction Display is still not available, so it's failed. But if I call it after calcRoute function, it's OK.
So, my question is, how can I know when the callback finish so that I can continue my work? I've tried putting a flag like below, but it was unsuccessful, the loop is infinite.
function calcRoute(start, end) {
var pStart = new google.maps.LatLng(start.lat(), start.lng());
var pEnd = new google.maps.LatLng(end.lat(), end.lng());
var pass = false;
var request = {
origin: pStart,
destination: pEnd,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
// Box the overview path of the first route
var path = result.routes[0].overview_path;
boxes = rboxer.box(path, distance);
//drawBoxes(boxes);
nearbyMarkets = search_market(boxes);
pass = true;
}
});
while (!pass) {
}
}
Observe the directions_changed-event:
google.maps.event.addListener(directionsDisplay, 'directions_changed',function(){
if(this.get('directions')){
//directions are available, do something
}
});
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.
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.