Google Maps: Given a point, how to find all points at a given road distance? - algorithm

In my app, the GPS picks the location of the vehicle. It is then supposed to put markers at all points where the vehicle could be if it drives for 1 KM in any direction (note that the roads may fork many times within his 1KM reach).
Can someone suggest me how to do this? Thanks in advance.

This is a very tricky problem to solve with the Google Maps API. The following is one method that you may want to consider:
You can easily calculate a bounding circle of 1km around your GPS point, and it is also easy to calculate points that fall on the circumference of this circle, for any angle. This distance will be "as the crow files" and not the actual road distance, but you may want to check out the following Stack Overflow post for a concrete implementation of this:
How to calculate the latlng of a point a certain distance away from another?
Screenshot with markers at 20 degree intervals on a bounding circle with a 1km radius:
removed dead ImageShack link - How to calculate the latlng of a point a certain distance away from another?
There is also a trick to snap these points to the nearest street. You can check out Mike Williams' Snap point to street examples for a good implementation of this.
Calculating the road distance from your GPS point to each snapped road point could be done with the directions service of the Google Maps API. Note that this will only work in countries that support directions in Google Maps, but more importantly, the road distance will almost always be greater than 1km, because our bounding circle has a 1km radius "as the crow flies". However if you can work with approximate information, this may already be one possible solution.
You can also consider starting with the above solution (1km bounding circle, calculate x points on the circumference, and snap them to the closest road), then calculate the road distance of each path (from your GPS point to each snapped point), and then you can repeat this this recursively for each path, each time using a smaller bounding circle, until you reach a road distance close to 1km. You can decrease the bounding circle in each recursion, in proportion to the error margin, to make your algorithm more efficient.
UPDATE:
I found a very neat implementation which appears to be using a similar method to the one I described above:
Driving Radius (Multiple destinations)
Note how you can change the interval of degrees from the top. With a wide interval you'll get fast results, but you could easily miss a few routes.
Screenshot:
removed dead ImageShack link - Driving Radius

Natural brute force algorithm is to build a list of all possible nodes taking into account each possible decision on every crossroad.
I doubt that within 1km you would get more then 10 crossroads on average and assuming avg of 3 choices on a crossroad you would end up with 3^10 - around 59,049 end nodes (notice that you need to have 10 crossroads on every branch of the road to reach the full number).
In reality the number would go down and I would assume getting to the same node by different route would not be uncommon, especially in cities.
This approach would give you an exact answer (providing you have good street map as input). It is potential time, but the n does not seem to be that high, so it might be practical.
Further improvements and optimizations might be possible depending on what do you need these nodes for (or which kind of scenarios you would consider similar enough to prune them).

Elaborating a bit on Daniel's approach above, you want to first find all the point within a straight line radius from your origin. That's your starting set of nodes. Now include ALL edges incident to those nodes and other nodes in your starting set. Now check that the nodes are connected and that there aren't any nodes out there floating around that you can't reach. Now create a "shortest path tree" starting from your vehicle node.
The tree will give you the shortest paths from your starting node to all other nodes. Note that if you start by creating paths at the furthest nodes, any sub-paths are also shortest paths to those nodes along the way. Make sure to label those nodes on sub-paths as you continue so you don't need to compute them. Worst case scenario, you need to develop a shortest path for all nodes, but in practice this should take much less time.

List all possible nodes taking into account each possible decision on every crossroad
(But how to do it automatically?
Use Dijkstra`s algorithm to find closes route to all points.
Visualize data.
(That is a little bit tricky, because there can be an unreachable areas inside reachable area.

Related

Identifying Number of Events

I have many rays, all whose start points are on a sphere in 3D, and whose direction vectors point inwards. Some of the rays are pointing towards a point A, others are pointing towards a point B, etc, with some noise (i.e. the rays don't perfectly intersect each other at their corresponding point A, B, etc).
Is there an algorithm that will allow me to determine how many points A,B, etc there are? Or even better, where those points are located? I don't know the locations of points A, B, etc, only the start points and direction vectors of the rays.
For example, is a sample setup, but in 2D, and I don't know which rays are pointing to which point (i.e. I don’t know which rays are red or blue). How would I find the number of points they’re pointing towards (two, in this example) or the locations of the points they're pointing towards?
I’ve tried a few different algorithms suggested in my earlier question, but they all seem to lose accuracy in identifying the locations of the points when the points are located close to each other. My first priority is just identifying the number of points with a high degree of accuracy even when they are located close together. Would that be possible, even if I have to sacrifice accuracy in locations?
Edit: If we let the radius of the sphere be 1000 units, then the error in the direction vector is about 10-20 units, while the min distance that the points can be apart for the algorithm to work currently is around 50 units. I don’t think this seems insurmountable, but I may very well be wrong.
I suggest that you treat this as a changing variant of the point-clustering problem.
First, make a set of points. Choose an approach threshold: how close should two rays come before you suspect that they refer to the same point? For each pair of rays that satisfies this threshold, insert a point at the midpoint of the segment of their closest approach. This is simple (?) 3D linear algebra.
Now, use your favorite cluster-counting algorithm to determine the quantity of clusters you have among these points. Your approach threshold will be highly significant in discriminating nearby points (see my comment).
Edit: thanks for the update in your question. The 50-unit separation in your data, compared to the 10-20 unit error, should allow you to discriminate "near" centroids using a density-sensitive clustering algorithm. Perhaps one of the spectral clustering methods will do the job for you.
You now have `k' identified clusters. Adapt the k-means clustering algorithm.
Choose the midpoint of each cluster as the centroid.
Delete all the "closest approach" points you made in the previous iteration. Keep the centroids.
Determine the cluster to which each ray belongs: your distance function is the closest approach of the ray to each of the centroids.
As you classify each ray, add to that cluster the point of that ray's closest approach to the centroid.
Repeat steps 1-4 until you've converged according to whatever epsilon criterion you have. The centroids are your targe points (A, B, etc.)
If you have any outliers, suspect that you are short a centroid.
If the centroids are too close (by whatever nearness criterion you can extract), then merge them.

Finding a possible path between 2 points with limited circle-ranges (algorithm)

I'm currently struggling in finding an algorithm if a path is possible or not.
I have a field of points, the positions of these points are fully random. I have also a starting point, and a destination point. On my starting point I can jump to any point around the starting point in a limited radius, and continue the same from there, but only with a limited amount of jumps. Performance in this case is important! Existant algorithms like Dijkstra won't help me here.
Any idea?
You could construct an undirected graph with the points as vertices. Each of the edges connects two points which are no further apart than the jump distance limit. Once this graph is constructed, you can find the shortest path with traditional algorithms.
To construct the graph, you could assign the points to a grid of 2D matrix cells. The cell hight and width is the jump radius limit. Candidate points for an edge for a given point have to belong to its matrix cell or directly adjacent cells. This reduces the construction time.
A further speedup could be to restrict a first version of the graph to those grid cells which are located near the direct line-of-sight between start and end point. Only if the search is not sucessfull, you could broaden the search area and try again.
If start and end point are further apart than radius limit times jump limit, no feasible path exists.
Just in case someone want have a solution:
Since the amount of jumps are limited I've created a radial grid, where the maximum radius is the amount of circles multiplied by their own radius.
After that I simply use an A-star path finder. (I used one existant by http://www.rapidfirestudio.com)

Find nearest delivery centers to a given area code

This was asked during interviewing process for a company. Suppose there is an interface to look for nearest delivery center to your area. All you have to enter is your zipcode/pincode and it returns the nearest delivery center. What would be the data structure and algorithm to do this? Like, you have broken your phone and want to go to a service center. You go to the company website and enter your zipcode to find out the nearest repair center. How does it do that?
I suggested a graph + hashmap solution where I will return the neighbouring nodes from a given node and addresses will be stored in hashmap w.r.t zipcodes but that wasn't good enough as the interviewer kept pressing on using the geographical property saying that you are not given the distance between two centers so how do you know which is the nearest and also if asked for top 3 nearest centers. I was not able to come up with any solution then. He was also asking me again and again what data you need to solve this thing. Would be really helpful to know what could be the approach for this as it has been bugging me for days. Thanks
Most algorithms deal with single points - just taking the centre point of a zip code area should suffice.
For a single nearest neighbour, a Voronoi diagram seem like the way to go.
It separates the space into regions such that, given any query point, we know which point is closest.
Taken from Wikipedia:
A kd-tree is also an option:
The k-d tree is a binary tree in which every node is a k-dimensional point. Every non-leaf node can be thought of as implicitly generating a splitting hyperplane that divides the space into two parts, known as half-spaces. Points to the left of this hyperplane are represented by the left subtree of that node and points right of the hyperplane are represented by the right subtree. The hyperplane direction is chosen in the following way: every node in the tree is associated with one of the k-dimensions, with the hyperplane perpendicular to that dimension's axis. So, for example, if for a particular split the "x" axis is chosen, all points in the subtree with a smaller "x" value than the node will appear in the left subtree and all points with larger "x" value will be in the right subtree. In such a case, the hyperplane would be set by the x-value of the point, and its normal would be the unit x-axis.
Finding the k nearest neighbours is significantly more difficult. There is a k nearest neighbours algorithm, but this is a classification algorithm, so I'm not sure it helps here.
One option is to create a grid of the region. Then, given a point, we know which cell it's in, and we can simply query that cell and its neighbours until we've found the desired number of neighbours.
One just has to be careful here, as the next nearest point can actually be in another cell, e.g.:
--------------
| B|
A | X |
| |
| |
--------------
Given point X, the closest point is A, but B would be returned if we simply look in the same cell. We also need to look at all neighbouring cells after we've found k points.
You need the whole road network which is a sparse matrix containing the distance between all of the nodes. You also need to have the list of nodes containing the service centers. Having this, I think the A* algorithm should do the job in determining the distance between a given location and each service center, then picking up the least three in distance. I am certain there are more efficient algorithms but I believe the interviewer should concentrate on the way you think to resolve a problem rather than asking for implementation details such as data structures. Would I have to solve such a problem in real life, I would do a literature research first.
I am not sure about what strategy is best when facing such interviewer and if he would have accepted such a response. Being assertive and providing an overview of the solution before diping into the details might have been better.
Do not have regrets though. Benefit from the experience and move on. You do not know what bounties God has in store for you.

Distance between lots of points on a map

I have a 20,000 point array of gps locations.
They represent points on a forest path that need to be checked. I need to figure out how many km of forest path needs checking.
Group the points into routes.
Measure the shorted path of each route
Which algorithms should I consider and in which order.
Should I get the shortest path and break it up into routes or get the routes and then find the shorted path of each.
This solution asumes that you only have the points and don't know on which forest path th e points are, and in which order, etc.
I would try it this way:
1 connect each node with each other with a link, and as link weight use the distance (or better the number of seconds when going with 2km/h in meters in between the nodes: low speed asuming walking in the wood is slower then on a existimg forest road)
2 if the forest has diffuclties (mountains, vallley, river):
2a: ascent/descent: raise the link weight, using the altitudinal difference, look in outdoor planning resources, how many meters ascent has impact to travellling time. (300m could be one addionional hour as rough estimate)
2b: valley, river or other limits: either again raise the weight or remove the link if one cannot directly go from one point to the other. (e.g draw the valley as polygon and remove all links that cross the polygon)
Are there already paths/ forest roads in the wood?
Yes, draw them as links into the modell (graph), to use link weight, e,.g 5km/h walking speed.
Now you have a graph with nodes and the links with hopefully realistic link weight related to travelling speed between nodes.
Now use Shortes path (Dijkstras Algorithm) and travelling salesman algorithm.
If that all is to much work (could be some months for somebody with a degree in computer science) , plan it manually: draw a raster of 1000 x 1000m and let the human intelligence
do its job.
Since 20.000 points which have to be checked by walking, needs a high effort, it is addionally worth to evaluate automatic planning versus human experience. Try both variants and look which is more efficient.
(I think that people with outdoor experience when having a good map with countour lines and the check points on it, will do a better job, asuming preorganizing by point two quadrants asignement and quadrants to people.)
My other soulution:
This asumes you have more info which you did not have yet posted:
You probably have more info than just the coordinates of the points.
Who has created this points? In your graphic, they look as they are on a path.
Are they recorded while driving on that path with a vehicle? Then you have a time stamp, and therefore an order of points that are in sequnce, and thefore already are related to a path.
So the first step would be to assign the points to a path.
(You also could draw all forest paths known as vectors to a digital map and match the points to the neareast path automatically)
You need the paths when you cannot directly reach each node on a straight line in betwwen them (e.g driving by vehicle or walking in wood when river avoids direct straight line path)
Then once you have a graph with nodes on links, use a minimum spaning tree to calculate the sum of path lengths in kilomter.
For visting the points you often will have to return to a branch, so then a travelling salesman algorith will help to give the kilomters needed to visit all nodes.
The question seems to be similar to a constrained vehicle routing problem. You can try a heuristic for example the savings algorithmus: http://neo.lcc.uma.es/vrp/solution-methods/heuristics/savings-algorithms/.

Find the point furthest away from n other points

I am trying to create an algorithm for 'fleeing' and would like to first find points which are 'safe'. That is to say, points where they are relatively distant from other points.
This is 2D (not that it matters much) and occurs within a fixed sized circle.
I'm guessing the sum of the squared distances would produce a good starting equation, whereby the highest score is the furthest away.
As for picking the points, I do not think it would be possible to solve for X,Y but approximation is sufficient.
I did some reading and determined that in order to cover the area of a circle, you would need 7 half-sized circles (with centers forming a hex, and a seventh at the center)
I could iterate through these, all of which are within the circle to begin with. As I choose the best scoring sphere, I could continue to divide them into 7 spheres. Of course, excluding any points which fall outside the original circle.
I could then iterate to a desired precision or a desired level.
To expand on the approach, the assumption is that it takes time to arrive at a location and while the location may be safe, the trip in between may not. How should I incorporate the distance in the equation so that I arrive at a good solution.
I suppose I could square the distance to the new point and multiply it by the score, and iterate from there. It would strongly favor a local spot, but I imagine that is a good behavior. It would try to resolve a safe spot close by and then upon re-calculating it could find 'outs' and continue to sneak to safety.
Any thoughts on this, or has this problem been done before? I wasn't able to find this problem specifically when I looked.
EDIT:
I've brought in the C# implementation of Fortune's Algorithm, and also added a few points around my points to create a pseudo circular constraint, as I don't understand the algorithm well enough to adjust it manually.
I realize now that the blue lines create a path between nodes. I can use the length of these and the distance between the surrounding points to compute a path (time to traverse and danger) and weigh that against the safety (the empty circle it is trying to get to) to determine what is the best course of action. By playing with how these interact, I can eliminate most of the work I would have had to do, simply by using the voronoi. Also my spawning algorithm will use this now, to determine the LEC and spawn at that spot.
You can take the convex hull of your set of locations - the vertices of the convex hull will give you the set of "most distant" points. Next, take the centroid of the points you're fleeing from, then determine which vertex of the convex hull is the most distant from the centroid. You may be able to speed this up by, for example, dividing the playing field into quadrants - you only need to test the vertices that are in the furthermost quadrant (e.g., if the centroid is in the positive-x positive-y quadrant, then you only need to check the vertices in the negative-x negative-y quadrant); if the playing field is an irregular shape then this may not be an option.
As an alternative to fleeing to the most distant point, if you have a starting point that you're fleeing from (e.g. the points you're fleeing from are enemies, and the player character is currently at point X which denotes its starting point), then rather than have the player flee to the most distant point you can instead have the player follow the trajectory that most quickly takes them from the centroid of the enemies - draw a ray from the enemies' centroid through the player's location, and that ray gives you the direction that the player should flee.
If the player character is surrounded then both of these algorithms will give nonsense results, but in that case the player character doesn't really have any viable options anyway.

Resources