Is $maxDistanceInKilometers broken? - parse-platform

I'm using parse REST api to query based on location. I'm using the following location queries
latitude = "-33.90483";
longitude = "151.2243";
When I use that, I got response objects. But when I try with the following location query, I got zero objects.
latitude = "-33.89";
longitude = "151.14";
I have this option as well -> "$maxDistanceInKilometers" = 20;
I used http://andrew.hedges.name/experiments/haversine/ to find distance between two coordinates but I found that they are just 7km away from each other so I should at least get some response objects from the second query.
Please let me know if I'm doing something wrong.
Thanks

Related

Get distance field from $geoNear aggregation in mongodb

I have the following aggregation command in my Spring project:
NearQuery query = NearQuery.near(longitude,latitude).maxDistance(distance).spherical(true);
agg = newAggregation(
geoNear(query, "distance"),
unwind("rate"),
group("id")
.first("name").as("name")
.sum("$rate.general_rate").as("rate")
.count().as("num_rates")
);
But when i made the mapped with my class, the distance field(from geoNear) is not exist. How can i pass in pipeline the distance to appear with others groups fields?
I faced the same :)
The answer is in your question..
geoNear(query, "distance"),
The above line will look for the property distance (type Double in case of Point) in the class which you are trying to aggregate the result.
Eg., output
"distance" : 420.82602810248557 (in meters)

How to get the full street address via the geocoder gem?

I am using geocoder with Google to validate addresses and give me back the correct values if they are munged slightly as well as to acquire latitude and longitude. I think I may be a bit off in my implementation here because it just feels so clunky and also I'm finding that some of the addresses are missing the street number.
I am starting off with the following code:
result = Geocoder.search(full_address_to_verify)
if result != []
street_address = result[0].address_components[1]["long_name"]
city = result[0].address_components[2]["long_name"]
state = result[0].address_components[5]["long_name"]
zip = result[0].address_components[7]["long_name"]
end
I have found that sometimes I get multiple results, and so I am going with the first one ([0] above). Further, I have found some queerness in that most of the time result[0].address_components[1] contains the full address, including the street_number, but once in a while it does not and I have to then add result[0].address_components[0]. I have yet to figure out a rhyme or reason to this.
Ultimately my goal here is to retrieve the USA street number + street, city, state and zip code fields into separate variables.
So my question is, is there a better way to retrieve the address so that the street number is always associated properly with the route?
From the documentation I'm not really seeing any clean methods that would just simply give me the desired address fields without pulling the data out of the individual fields from the request reply...
A couple of years late to the party. Extracting an address from the google geocoding API is straightforward and rather cumbersome with the nested address_components.
Luckily, the geocoder gem has built-in methods to access the address info. Read more on the docs.
Right, the address_components should enable you to do what you want to accomplish. For the rhyme, you can refer to this part of the documentation about address type.
Google Maps API marked which kind of the component this field belong by putting a string in this location:
result[0].address_components[i].types[0]
You should get your correspond values based on the types, but not the position of the address_components.
This is how Google approached it in their Places Autocomplete API demo:
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
...
...
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}

How to handle simple geospatial queries (distances) in ruby with activerecord-postgis-adapter?

I've got a lot of lat / lon points in a csv file, I've created a table which has a point in the 4326 projection (table postcode, field location)
I'm building data like this:-
factory = ::RGeo::Cartesian.preferred_factory(:has_z_coordinate => false)
p = factory.point(data_hash[:latitude], data_hash[:longitude])
and storing p in the location field.
The issue then is that I want to find "near" records to a given point.
I've seen some promising code at:-
https://github.com/rgeo/activerecord-postgis-adapter/blob/master/test/spatial_queries_test.rb
so I wrote the following:-
factory = ::RGeo::Cartesian.preferred_factory(:has_z_coordinate => false)
p = factory.point(53.7492, 1.6023)
res = Postcode.where(Postcode.arel_table[:location].st_distance(p).lt(1000));
res.each do |single|
puts single.postcode
end
But I'm getting exceptions (unsupported: RGeo::Cartesian::PointImpl)
I assume I'm needing to do some converting or something, any pointers appreciated!
I think your problem lies in the factory you use. Try to generate point from a spherical factory:
p = RGeo::Geographic.spherical_factory(srid: 4326).point(53.7492, 1.6023)
Also check rails logs to see the output query and run it manually in PG. Make sure that the query runs without problems.

FOSElasticaBundle order query

I am integrating FOSElasticaBundle in my Symfony 2.3 project and I need to sort the results by their price property.
Here is my code:
$finder = $this->container->get('fos_elastica.finder.website.product');
$fieldTerms = new \Elastica\Query\Terms();
$fieldTerms->setTerms('taxon_ids', $taxon_ids_array);
$boolQuery->addMust($fieldTerms);
$resultSet = $finder->find($boolQuery);
How I can do this?
Thanks
Try create a \Elastica\Query object which also contains the sorting information, then send this to the finder:
$finder = $this->container->get('fos_elastica.finder.website.product');
$fieldTerms = new \Elastica\Query\Terms();
$fieldTerms->setTerms('taxon_ids', $taxon_ids_array);
$boolQuery->addMust($fieldTerms);
$finalQuery = new \Elastica\Query($boolQuery);
$finalQuery->setSort(array('price' => array('order' => 'asc')));
$resultSet = $finder->find($finalQuery);
Have a look at the elasticsearch docs on the sort parameter to see how to use it properly.
NOTE: \Elastica\Query is quite different to \Elastica\Query\AbstractQuery, the first encapsulates everything you could send to the _search API endpoint (facets, sorting, explain, etc...) The AbstractQuery represents a base type for each of the individual query types (range, fuzzy, terms, etc...).

Getting all zip codes within an n mile radius

What's the best way to get a function like the following to work:
def getNearest(zipCode, miles):
That is, given a zipcode (07024) and a radius, return all zipcodes which are within that radius?
There is a project on SourceForge that could assist with this:
http://sourceforge.net/projects/zips/
It gives you a database with zip codes and their latitude / longitude, as well as coding examples of how to calculate the distance between two sets of coordinates. There is probably a better way to do it, but you could have your function retrieve the zipcode and its coordinates, and then step through each zipcode in the list and add the zipcode to a list if it falls within the number of miles specified.
If you want this to be accurate, you must start with polygon data that includes the location and shape of every zipcode. I have a database like this (used to be published by the US census, but they no longer do that) and have built similar things atop it, but not that exact request.
If you don't care about being exact (which I'm guessing you don't), you can get a table of center points of zipcodes and query points ordered by great circle distance. PostGIS provides great tools for doing this, although you may construct a query against other databases that will perform similar tasks.
An alternate approach I've used is to construct a box that encompasses the circle you want, querying with a between clause on lon/lat and then doing the great-circle in app code.
Maybe this can help. The project is configured in kilometers though. You can modify these in CityDAO.java
public List<City> findCityInRange(GeoPoint geoPoint, double distance) {
List<City> cities = new ArrayList<City>();
QueryBuilder queryBuilder = geoDistanceQuery("geoPoint")
.point(geoPoint.getLat(), geoPoint.getLon())
//.distance(distance, DistanceUnit.KILOMETERS) original
.distance(distance, DistanceUnit.MILES)
.optimizeBbox("memory")
.geoDistance(GeoDistance.ARC);
SearchRequestBuilder builder = esClient.getClient()
.prepareSearch(INDEX)
.setTypes("city")
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setScroll(new TimeValue(60000))
.setSize(100).setExplain(true)
.setPostFilter(queryBuilder)
.addSort(SortBuilders.geoDistanceSort("geoPoint")
.order(SortOrder.ASC)
.point(geoPoint.getLat(), geoPoint.getLon())
//.unit(DistanceUnit.KILOMETERS)); Original
.unit(DistanceUnit.MILES));
SearchResponse response = builder
.execute()
.actionGet();
SearchHit[] hits = response.getHits().getHits();
scroll:
while (true) {
for (SearchHit hit : hits) {
Map<String, Object> result = hit.getSource();
cities.add(mapper.convertValue(result, City.class));
}
response = esClient.getClient().prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
if (response.getHits().getHits().length == 0) {
break scroll;
}
}
return cities;
}
The "LocationFinder\src\main\resources\json\cities.json" file contains all cities from Belgium. You can delete or create entries if you want too. As long as you don't change the names and/or structure, no code changes are required.
Make sure to read the README https://github.com/GlennVanSchil/LocationFinder

Resources