Reputation: 223
I'm need some help with load nearest shops. Currently I implemented to load all the shops from json which contains lat & long. But now I wanted to load all shops within 5km from current location. Some people suggest me to use distanceTo() for that, but I couldn't implement it. Please someone help with this issue?
Following code loads all the shops from the json (Works fine):
for(final Shop shop : this.response.shops){
for(int i = 0; i < shop.getShopLat().size(); i++){
map.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(shop.getShopLat().get(i)), Double.parseDouble(shop.getShopLng().get(i)))).title(shop.getName()));
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoContents(Marker marker) {
// TODO Auto-generated method stub
return null;
}
@Override
public View getInfoWindow(Marker marker) {
// TODO Auto-generated method stub
return null;
}
});
}
}
Edited:
LocationManager service = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location userLocation = service.getLastKnownLocation(provider);
Upvotes: 0
Views: 642
Reputation: 2363
First, you have to get the users location, there are many ways to achieve that, and it isn't as simple as it looks if you want to get the best and most accurate location, check this thread, really helpful, after that I think you should use something like this:
float[] results = new float[3];
Location.distanceBetween(userLocation.getLatitude(), userLocation.getLongitude(), Double.parseDouble(shop.getShopLat().get(i), Double.parseDouble(shop.getShopLng().get(i)), results);
//results[0] = distance in meters
So just put an if inside the for statement.
for(final Shop shop : this.response.shops){
for(int i = 0; i < shop.getShopLat().size(); i++){
float[] results = new float[3];
Location.distanceBetween(userLocation.getLatitude(), userLocation.getLongitude(), Double.parseDouble(shop.getShopLat().get(i), Double.parseDouble(shop.getShopLng().get(i)), results);
if(results[0]<=5000)
{
map.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(shop.getShopLat().get(i)), Double.parseDouble(shop.getShopLng().get(i)))).title(shop.getName()));
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter()
{
@Override
public View getInfoContents(Marker marker) {
// TODO Auto-generated method stub
return null;
}
@Override
public View getInfoWindow(Marker marker) {
// TODO Auto-generated method stub
return null;
}
});
}
}
}
Upvotes: 0
Reputation: 5134
U can use google api to achieve this
StringBuilder sb = new StringBuilder(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + latitude + "," + longitude);
sb.append("&radius=5000");
sb.append("&types=" + placeType);
sb.append("&sensor=true");
sb.append("&key=Your Api Key");
here is a nice link , you can follow this
Upvotes: 1