-2

i am trying to make an application where it show the 5 closest places with multiple markers from my current location. On other topics i saw many examples, but, no one explained how to create app with multiple markers or HashMap where show the nearest place. Please help me to solve it.

Here is my Main activity.java

public class MainActivity extends Activity
{
    private GoogleMap mMap;
    private ArrayList<MyMarker> mMyMarkersArray = new ArrayList<MyMarker>();
    private HashMap<Marker, MyMarker> mMarkersHashMap;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mMarkersHashMap = new HashMap<Marker, MyMarker>();

mMyMarkersArray.add(new MyMarker("Restaurant Zaplet", "Telephone:   \n Address: ", "iconZaplet", Double.parseDouble("43.381499"), Double.parseDouble("19.808931")));
mMyMarkersArray.add(new MyMarker("Restaurant Oresac", "Telephone:   \n Address: ","iconOresac", Double.parseDouble("43.796009"), Double.parseDouble("21.745934")));
mMyMarkersArray.add(new MyMarker("Restaurant Obilic","Telephone:  \n    Address: ", "iconObilic", Double.parseDouble("42.547670"), Double.parseDouble("19.660000")));
mMyMarkersArray.add(new MyMarker("Restaurant Dva sesira","Telephone:    \n Address: XII vek", "iconDvaSesira", Double.parseDouble("41.486736"), Double.parseDouble("20.731670")));
mMyMarkersArray.add(new MyMarker("Manastir Lipov Lad", "Telephone:  \n Address: ","iconLipovLad", Double.parseDouble("44.850546"), Double.parseDouble("20.479869")));
mMyMarkersArray.add(new MyMarker("Restaurant Slodes", "Telephone: nepoznato \n Address: ", "iconSlodes", Double.parseDouble("41.503238"), Double.parseDouble("19.791890")));

    setUpMap();

    plotMarkers(mMyMarkersArray);

}

private void plotMarkers(ArrayList<MyMarker> markers)
{
    if(markers.size() > 0)
    {
        for (MyMarker myMarker : markers)
        {

            MarkerOptions markerOption = new MarkerOptions().position(new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude()));
            markerOption.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_restaurant));

            Marker currentMarker = mMap.addMarker(markerOption);
            mMarkersHashMap.put(currentMarker, myMarker);

            mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());

        }
    }
}

private int manageMarkerIcon(String markerIcon)
{
    if (markerIcon.equals("iconZaplet"))
        return R.drawable.zaplet;
    else if(markerIcon.equals("iconOresac"))
        return R.drawable.oresac;
    else if(markerIcon.equals("iconObilic"))
        return R.drawable.obilic;
    else if(markerIcon.equals("iconLipovLad"))
        return R.drawable.lipovlad;
    else if(markerIcon.equals("iconSlodes"))
        return R.drawable.slodes;
    else
        return R.drawable.icondefault;
}


private void setUpMap()
{
    if (mMap == null)
    {
        mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();


        if (mMap != null)
        {
            mMap.setMyLocationEnabled(true);

            LocationManager lm = (LocationManager) getSystemService (LOCATION_SERVICE);

            String provider = lm.getBestProvider(new Criteria (), true);

            if (provider == null) {
                onProviderDisabled (provider);
            }

            Location loc = lm.getLastKnownLocation(provider);
            if (loc != null) {
                onLocationChanged (loc);
            }


            mMap.setOnMapLongClickListener(onLongClickMapSettings ());
            mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
            {
                @Override
                public boolean onMarkerClick(com.google.android.gms.maps.model.Marker marker)
                {
                    marker.showInfoWindow();
                    return true;
                }
            });
        }
        else
            Toast.makeText(getApplicationContext(), "Unable to create Maps", Toast.LENGTH_SHORT).show();
    }
}

private OnMapLongClickListener onLongClickMapSettings() {
    // TODO Auto-generated method stub
    return new OnMapLongClickListener () {

        @Override
        public void onMapLongClick(LatLng arg0) {
            // TODO Auto-generated method stub
            Log.i(arg0.toString(), "User long clicked");

        }

    };
}

public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

    LatLng latlng = new LatLng (location.getLatitude(), location.getLongitude());

    mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(10));

}


public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}


public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}


public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter
{
    public MarkerInfoWindowAdapter()
    {
    }

    @Override
    public View getInfoWindow(Marker marker)
    {
        return null;
    }


    @SuppressLint("InflateParams") @Override
    public View getInfoContents(Marker marker)
    {
        View v  = getLayoutInflater().inflate(R.layout.info_window_layout, null);

        MyMarker myMarker = mMarkersHashMap.get(marker);

        ImageView markerIcon = (ImageView) v.findViewById(R.id.marker_icon);

        TextView markerLabel = (TextView)v.findViewById(R.id.marker_label);

        TextView anotherLabel = (TextView)v.findViewById(R.id.another_label);

        markerIcon.setImageResource(manageMarkerIcon(myMarker.getmIcon()));

        markerLabel.setText(myMarker.getmLabel());
        anotherLabel.setText(myMarker.getmIstorijat());

        return v;
    }
}

}

Here is code of MyMarker.java

> public class MyMarker
{
    private String mLabel;
    private String mIstorijat;
    private String mIcon;
    private Double mLatitude;
    private Double mLongitude;

public MyMarker(String label, String istorijat, String icon, Double latitude, Double longitude)
{
    this.mLabel = label;
    this.mIstorijat = istorijat;
    this.mLatitude = latitude;
    this.mLongitude = longitude;
    this.mIcon = icon;
}

public String getmLabel()
{
    return mLabel;
}

public void setmLabel(String mLabel)
{
    this.mLabel = mLabel;
}

public String getmIstorijat()
{
    return mIstorijat;
}

public void setmIstorijat(String mIstorijat)
{
    this.mIstorijat = mIstorijat;
}

public String getmIcon()
{
    return mIcon;
}

public void setmIcon(String icon)
{
    this.mIcon = icon;
}

public Double getmLatitude()
{
    return mLatitude;
}

public void setmLatitude(Double mLatitude)
{
    this.mLatitude = mLatitude;
}

public Double getmLongitude()
{
    return mLongitude;
}

public void setmLongitude(Double mLongitude)
{
    this.mLongitude = mLongitude;
}

}

Veljko P.
  • 89
  • 5
  • 1
    What exactly is going wrong with the code? – nasch May 04 '15 at 19:31
  • The code is correct, but i don't know how to set that show me the nearest place of my current location – Veljko P. May 04 '15 at 19:35
  • I don't see your requestLocationUpdates(...) and you manually call onLocationChanged(...) with lm.getLastKnownLocation(provider); ... Does it work? I don't think getLastKnownLocation should return a location if you didn't request updates. And the onLocationChanged method of a LocationListener is automatically called on locatonUpdates if you set the LocationListener with requestLocationUpdates. – Damien May 05 '15 at 16:22
  • I would suggest you have a look at http://developer.android.com/guide/topics/location/strategies.html – Damien May 05 '15 at 16:24
  • I would also suggest that you use "@Override" annotations because you seem to want your activity to override methods of LocationListener but it doesn't implement this interface. And "@Override" will generate an error that will help you to see that you forgot to implement this interface. – Damien May 05 '15 at 16:29

1 Answers1

0

I'm sorry but I don't really understand your problem here. It seems that you know how to recover the map marker with you MyMarker object using HashMap. And you are also able to create all the markers you need. Since your question is about creating an application with HashMap and multiple markers, it seems that you already have done that. Unless your code doesn't work but in this situation it would be helpfull if you told us about what it does exactly.

I'm not sure about what you are asking, but I believe that you have 5 marker, and you want to get the closest one. If your question is how to do that then I think you just have to loop on every marker and calculate their distance with the user's position to find the smallest one.

If you don't know how to calculate the distance, I personnaly use the distanceTo(Location) method of Location. Maybe it is not the best code but here is what it looks like :

public static double distanceTo(LatLng from, LatLng to) {
    Location locationA = new Location("");
    locationA.setLatitude(from.latitude);
    locationA.setLongitude(from.longitude);
    Location locationB = new Location("");
    locationB.setLatitude(to.latitude);
    locationB.setLongitude(to.longitude);
    return locationA.distanceTo(locationB) / 1000;
}

You can for example do something like that :

Marker closest = null;
double minDistance;
for(Marker m : mMarkersHashMap.keySet()){
    double distance = distanceTo(currentPos, m.getPosition())
    if(closest == null || minDistance > distance){
        closest = m;
        minDistance = distance;
    }
}

Wrote it quickly and haven't tested it but if you want to do it for the 5 closest markers I think this works :

Marker[] closest = new Marker[5];
double[] minDistance = new double[5];
for(Marker m : mMarkersHashMap.keySet()){
    double distance = distanceTo(currentPos, m.getPosition())
    for(int i = 4; i >=0; i--){
        if(closest[i] == null || minDistance[i] > distance){
            if(i < 4){
                closest[i+1] = closest[i];
                minDistance[i+1] = minDistance[i];
            }
            closest[i] = m;
            minDistance[i] = distance;
        } else {
            break;
        }
    }
}
Damien
  • 141
  • 1
  • 6
  • I want that app show 5 closest markers, because I will expand number of markers on HashMap. How could I app method of calucalte the distance that you show me on my example? – Veljko P. May 04 '15 at 22:53
  • How could I apply distanceTo on my app? Is there any way except that I have to loop on every marker? – Veljko P. May 04 '15 at 23:05
  • "If your question is how to do that then I think you just have to loop on every marker and calculate their distance with the user's position to find the smallest one." I agree, no other way to find the closest markers to a given position. – nasch May 04 '15 at 23:08
  • I try to tested your code, but I have error in row double distance = distanceTo(currentPos, m.getPosition()) because currentPos cannot resolve as variable. What I should to do? – Veljko P. May 06 '15 at 03:24
  • currentPos is the current location of thé user. You can either get it from getlastknownlocation, or it is also sent to the locationlistener set with requestlocationupdates – Damien May 06 '15 at 06:12