Generate list of street Intersections in order - google-maps

I have a list of all intersections in a city with coordinates. I am trying for an end result of a list of all the intersections in the order they appear. For example, if I put in Alameda & 5th - I want to see all cross streets if I keep going down Alameda (ex Alameda & 6th, Alameda & 7th, etc. )
However, they aren't all numbered streets.
I need the final format to be text-based - no visual mapping. I'm quite stumped on how to start and hoping for some direction.

Solution 1:
I would recommend using the longitude and latitude and ordering it by that. For instance, you can tell if a street is "below" another if the latitude of it is less than the other one. That'll probably get most of them in the right spot.
You can then manually double check them if there's not too much data.
Solution 2:
If there's not that much data, you might want to simply do it by hand. This isn't very efficient, but it could save your time (again, depending on the amount of data you have).

It sounds like you need to just create a relational database. My suggestion would be to get familiar (if you are not already) with Microsoft access. I can't think of any other tool that would suite you better.
All you would have to do is paste the list of intersections you already have into a table, create another table for the cross streets then, just make them relational. After that create your queries to spit out whatever data you want.
You will also have the opportunity to create a sort order of the cross streets relative to each intersection.
If you haven't used Access before, there is a bit of a learning curve but it's not like coding. Just watch a few youtube videos or invest in a Udemy coarse. I created a very similar database within a couple of days myself.

I am trying a pseudo implementation based on the limited information you have given.
Let's have Street and Intersection classes and some Database that can be queried for a list of objects with where filters (think of it as some SQL wrapper).
Now, we need a sorting algorithm for the intersections. The problem here is, that we cannot know the physical order based on the given information. Roads may go in curves, tunnels and what not.
So the next best thing we can do is guessing the order by evaluating the distance. Note that this will only work in a Manhattan type map layout without curves.
We will arbitrarily assume the first intersection would be the one with the lowest coordinate value.
From there, we search all our streets remaining intersections for the closest to the previous.
Again, please be aware, that this algorithm is a guess based on the given information. However, the general implementation pattern should still be usable for more sophisticated algorithms or the incorporation of additional information.
Please see my implementation in pseudo-code:
Database {
allIntersections {...}
allStreets {...}
}
Street {
id: String
name: String
intersections() -> [Intersection] {
return Database.allIntersections.where(street1 == self || street2 == self)
}
lowestIntersection() -> Intersection {
lowestIntersection: Intersections().first
for intersection in Intersections() {
currentDistance = intersection.distanceTo(Coordinate(0,0))
if (currentDistance < lowestIntersection.distanceTo(Coordinate(0,0)) {
lowestIntersection = intersection
}
}
return lowestIntersection
}
// the sort algorithm based on proximity
sortedIntersections() -> [Intersection] {
sorted = [lowestIntersection()]
remaining = intersections() - sorted
while remaining.count > 0 {
closest = sorted.last.closestIntersection(remaining)
remaining.remove(closest)
sorted.add(closest)
}
return sorted
}
}
Coordinate {
lat: Float
long: Float
}
Intersection {
street1: Street
street2: Street
coordinate: Coordinate
distanceTo(other: Coordinate) -> Float {
return sqrt(pow2(coordinate.lat - other.lat) + pow2(coordinate.long - other.long))
}
closesIntersection(others: Intersection) -> Intersection {
closesIntersection: others.first
for intersection in others {
currentDistance = intersection.distanceTo(self.coordinate)
if (currentDistance < closesIntersection.distanceTo(self.coordinate) {
closesIntersection = intersection
}
}
return closesIntersection
}
}
I hope this helps. For a more detailed answer, please provide more information like example data.

Related

google map placing locations with some distance

I'm new to ROR and Google Maps. I need to place some markers from locations in Google Maps (having latitudes and longitudes in a database).
The problem is that I need to select some points with some random distance.
In short, I need to select the location and place it in a map, which must have 100 m distance with each and every points.
If the location is within 100 m range with any other points, it can be neglected. I need to place 10 points from database.
Is there any method?
Assuming that you are needing to find points from your database that are at least 100 meters away from all the other points in the database:
This is a fairly simple problem. It can be visualized as an nxn matrix, with the point set as the rows and columns. In Python, comparing all the distances would look like:
selected = []
for pt1 in pts:
inRange = True
for pt2 in pts:
if pt1.distanceTo(pt2) < 100:
inRange = False
break
if inRange:
selected.append(pt1)
This function iterates through the whole list of points. For each point, it checks the distance from the current point to all the other points. If all the other points are outside 100 meters, it adds the point to an array.
For the distance formula, please see the haversine formula here in code form.
Since you did not specify a language in your question, I will let you translate this into whatever language you need. This is just pseudocode, since not enough details were provided to answer your question with actual code.
Also, if I misunderstood your question, you can adapt this algorithm in some way. It is just to provide some ideas.

GPS coordinations for each kilometer

I'll find a route between two places, for example using google maps. I'd like to divide the route to kilometers (two following places will be at a distance of 1 km), and get GPS coordinations of these places. This is because then I'll be able to get exacly the coordinations of, for example, 5th kilometer on the route. Could you please advice me how to achieve it?
This is extremely nontrivial. Is say your best bet is to find an algorithm to load the bearing between two points, then one to load a coordinate given a start point, distance, and bearing. This could give you it, but only if the data contained only straight lines. Since I assume the Google Maps API only gives you the turns the user has to make, this approach will be inaccurate when there are bends in roads. You'd need GIS data for roads and what will undoubtedly turn into a complicated algorithm to find something like this. It's definitely doable, but that's l how I'd start. Look into the Census TIGER road data, it should help.
Unless, of course, I'm wrong and the API does actually give enough points to cleanly map it, in which case those functions should be easy to find and implement.
This will only work if you have the polyline as a sequence of lat/lon (or other) coordinates, wherever you get that from.
Then you start at the beginning an iterate through the lines (point[i], point[i+1]).
THis distance you calculate with standard API.
while itersting you sum up the distance.
Once you exceed the 1000m, you know that the splitting point (the 1000m marker) is at line segment [i,i+1].
To calculate the exact position where on the line that is, you take the total summed meters from previous segment, and the value of this segment and do a linear interpolation.
The working code is a bit complexer: there can be multiple markes within one segement.
But first find out where you get the polyline from, whitou that it will not work.

Where can I find city/town location data for location-based searching?

I need to implement find entries with x miles of town function, so I have a town box with autosuggest attached. Currently I'm using Google's Geocoding API to get the data for the autosuggest results, but we obviously can't tune or alter this data and it doesn't always come up with sensible suggestions (even with a country hint). Are there any other sources of town/city location data? I've tried to see if perhaps an export was available from OpenStreetMap or something but I can only find map tiles or vector map data and not POI data for town/city names and locations.
Any suggestions appreciated.
Thanks.
Geonames.org has a downloadable list of cities and even postal codes for many countries around the world along with their corresponding lat/lon point. It's under the Creative Commons Attribution 3.0 License which means that you can use it commercially, but you have to give attribution, among other things.
While having a downloadable list may mean more work on your end in terms of implementing all of the facets of the search algorithm, the silver lining is that you don't couple yourself to the uptime/availability of a 3rd-party web service.
The only other part that's missing is the distance-calculation formula. You can use the greater-circle distance formula to compute distance.
I've done this myself a number of times. The first time you write the code, it takes a little bit to wrap your head around everything, but once you do it's a piece of cake thereafter.
I should probably mention that I'm the founder of SmartyStreets. We do street-based address verification and not only can we tell you if an address is good or not (which helps in a significant number of ways), but we can also give you the lat/lon coordinate for a given street address which can then be plugged in to the above solution to determine proximity to nearby places.
I would say you also have two other options to get the functionality you require.
Firstly, you can use a kludge to focus the results to more meaningful ones (although I would not strongly recommend this method it may suffice for your needs.)
Before your initial query to Google's Geocoding API to get the data for the autosuggest results, firstly determine the country the town is in. Then you can use the country string as a suffix to the Geocoding query.
Something like:
var country = 'UK'; // from initial query, reverse geocode, etc.
geocoder.geocode({
'address': address + ', ' + country
},
See the answer in this question for an example.
Google's Geocoder returns wrong country, ignoring the region hint
Secondly, the premise that you "obviously can't tune or alter this data" is flawed. You can certainly filter the results based on the country. Something like the following snippet shows how to drill down the results.
geocoder.geocode({
'address': address
},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
for(var i = 0, l = results.length; i < l; i++) {
for (var j = 0, l2 = results[i].address_components.length; j < l2; j++) {
for (var k = 0, l3 = results[i].address_components[j].types.length; k < l3; k++) {
if(results[i].address_components[j].types[k]=="country") {
var country = results[i].address_components[j].long_name;
// do stuff based on the country
// add the result to your auto-suggest, etc...
}
}
}
}
});
}
Finally, if you implemented a CGI wrapper to do the geocoding you could cache the results. This way your application would automatically build your database for you. This would save actually having to perform geocoding at all for known results. I think this is almost what you are hinting at in your question, and there is no reason you could not pre-populate your cache with known results if you did find a reliable source of data.
Take a look at this document that outlines various Geocoding Strategies using the Maps Api - it discusses things like caching, etc.
https://developers.google.com/maps/articles/geocodestrat
EDIT
You could use something like geoPlugin
http://www.geoplugin.com/webservices/php#php_class
Take a look at the nearby places features, this does exactly what you want.
http://www.geoplugin.com/webservices/extras
Check out http://geohash.org/, this site working with many api's that you may want to use. See also the article about the history of this site

Does the v3 Google Maps Geocoding API have a field that represents accuracy?

I have some code that I'm porting over from API v2 to v3. In the old code we had an accuracy field that came back in the xml (not sure of the name, but it did represent a confidence level of sorts). In the new API, I don't see any field like that.
If I put "Oregon, USA" into the search field I get 5 matches. The first 2 are "Oregon, USA" and "Oregon, OH, USA". They both have "partial_match" = false. This doesn't seem right, one seems partial and one doesn't. Plus, they're both coming back with the same "location_type" (APPROXIMATE). In fact, all matches are showing as not-partial and have same location type.
My question is, do any of the fields in the result set convey some sort of confidence in the accuracy of the result? In my sample it really seems like one result is much more accurate than any other -- so much so that the input string exactly matches the QuickAddress field that's returned.
Two weeks, no answers, so here's my solution.
The API will return either ROOFTOP, GEOMETRIC_CENTER, RANGE_INTERPOLATED or APPROXIMATE.
Rooftop is essentially "dead on" -- the API resolved the address to a building. Other than that, you get varying degrees of "close". My solution was to use the bounding box that was returned to determine how close close was. So if you ask for a street (Avenue of the Americas, NY, NY) you'll get a huge bounding box. Ask for an address on that street that the API thinks is an actual address but isn't a Rooftop, you'll get a very small bounding box. I used the area of the bounding box to determine the accuracy of the result. My accurate/not accurate break was at 0.9E-6 but I think you'd have to tinker with it to make sure you are comfortable with that number.
I have found this useful when updating legacy V2 code dependent on a 0 to 9 score
//Hack to convert location_type (string) to 0-9 Geocode score as 0-9 Geocode score doesn't exist in v3 API
function get_numeric_score(results) {
switch(results[0].geometry.location_type){
case "ROOFTOP":
return 9;
break;
case "RANGE_INTERPOLATED":
return 7;
break;
case "GEOMETRIC_CENTER":
return = 6;
break;
case "APPROXIMATE":
return 4;
break;
default:
return 0;
}
}

Locating all elements between starting and ending points, given by value (not index)

The problem is as follows,
I would be given a set of x and y coordinates(an coordinate array of around 30 to 40 thousand) of a long rope. The rope is lying on the ground and can be in any shape.
Now I would be given a start point(essentially x and y coordinate) and an ending point.
What is the efficient way to determine the set of x and y coordinates from the above mentioned coordinate array lie between the start and end points.
Exhaustive searching ie looping 40k times is not an acceptable solution (mentioned on the question paper)
A little bit margin for error is acceptable
We need to find the start point in the array, then the end point. For each, we can think of the rope as describing a function of distance from that point, and we're looking for the lowest point on that distance graph. If one point is a long way away and another is pretty close, we can do some kind of interpolation guess of where to search next.
distance
| /---\
|-- \ /\ -
| -- ------- -- ------ ---------- -
| \ / \---/ \--/
+-----------------------X--------------------------- array index
In the representation above, we want to find "X"... we look at the distances at a few points, get an impression of the slope of the distance curve, possibly even the rate of change of that slope, to help guide our next bit of probing....
To refine the basic approach of doing binary- or interpolated- searches in areas where we know the distance values are low, we may be able to use the following:
if we happen to be given the rope length and know the coordinate samples are equidistant along the rope, then we can calculate a maximum change in distance from our target point per sample.
if we know the rope has a stiffness ensuring it can't loop in a trivially small diameter, then
there's a known limit to how fast the slope of the curve can change
distance curve converges to vertical on both sides of the 0 point
you could potentially cross-reference/combine distance with, or use instead, the direction of each point from the target: only at the target would the direction instantly change ~180 degrees (how well the data points capture this still depends on the distance between adjacent samples and any stiffness of the rope).
Otherwise, there's always risk the target point may weirdly be encased by two very distance points, frustrating our whole searching algorithm (that must be what they mean about some margin for error - every now and then this search would have to revert to a O(N) brute-force search because any trend analysis fails).
For a one-time search, sometimes linear traversal is the simplest, fastest solution. Maybe that's the case for this problem.
Iterate through the ordered list of points until finding the start or end, and then collect points until hitting the other endpoint.
Now, if we expected to repeat the search, we could build an index to the points.
Edit: This presumes no additional constraints beyond those mentioned by #koool. Constraining the distance between the points would allow the hill-climbing approach described in #Tony's answer.
I don't think you can solve it accurately using anything other than exhaustive search. Say for cases where the rope is folded into half and the resulting double rope forms a spiral with the two ends on the centre.
However if we assume that long portions of the rope are in straight line, then we can eliminate a lot of points based on the slope check:
if (abs(slope(x[i],y[i],x[i+1],y[i+1])
-slope(x[i+1],y[i+1],x[i+2],y[i+2]))<tolerance)
eliminate (x[i+1],y[i+1]);
This will reduce the search time significantly if large portions of the rope are in straight line. But will be linear WRT number of remaining points.
So basically, you've got a sorted list of the points that comprise the entire rope and you're given two arbitrary points from within that list, and tasked with returning the sublist that exists between those two points.
I'm going to make the assumption that the start and end points that are provided are guaranteed to coincide exactly with points within the sorted list (otherwise it introduces a host of issues, particularly if the rope may be arbitrarily thin and passes by the start/end points multiple times).
That means all you're really looking for are the indices of the two provided coordinates. Or the index of one, and the answer to "is the second coordinate to the right or to the left?".
A simple O(n) solution to that would be:
For each index in array
coord = array[index]
if (coord == point1)
startIndex = index
if (coord == point2)
endIndex = index
if (endIndex < startIndex)
swap(startIndex, endIndex)
return array.sublist(startIndex, endIndex)
Or, if you wanted to optimize for repeated queries, I'd suggest a hashing based approach where you map each cooordinate to its index in the array. Something like:
//build the map (do this once, at init)
map = {}
For each index in array
coord = array[index]
map[coord] = index
//find a sublist (do this for each set of start/end points)
startIndex = map[point1]
endIndex = map[point2]
if (endIndex < startIndex)
swap(startIndex, endIndex)
return array.sublist(startIndex, endIndex)
That's O(n) to build the map, but once it's built you can determine the sublist between any two points in O(1). Assuming an efficient hashmap, of course.
Note that if my assumption doesn't hold, then the same solutions are still usable, provided that as a first step you take the provided start and end points and locate the points in the array that best correspond to each one. As noted, unless you are given some constraints regarding the thickness of the rope then interpolating from an arbitrary coordinate to one that's actually part of the rope can only be guesswork at best.