Jayson John Jayson John - 1 year ago 116
Android Question

Android show marker onClick button

I want to plot all the coordinates of latitude and longitude values I get. Check the first and last of the plot and change with different icons. Add Poly lines on each mark plot and buttons on popup that can hide/dismiss.

The problem I am having now is that whenever I remove the for-loop outside the button I am having a null pointer error.

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map1);
mapFragment.getMapAsync(this);

new GetVehicleValue().execute();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_contact_us, container, false);
Button b = (Button) v.findViewById(R.id.button3);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

}
});

if(vehicleHolder.size() != 0) {
for(int i =0; i < vehicleHolder.size(); i++) {
createMarker(i,vehicleHolder.get(i).getLatitude(),vehicleHolder.get(i).getLongitude(),vehicleHolder.get(i).getVehicle());
}
}

return v;
}

public void createMarker(int index, String latitude, String longitude, String vehicle) {
// Adding the taped point to the ArrayList
BitmapDescriptor image = BitmapDescriptorFactory.fromResource(R.drawable.bus);
Double lat = Double.parseDouble(latitude);
Double Longitude = Double.parseDouble(longitude);
float color = 0;

mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, Longitude))
.anchor(0.5f, 0.5f)
.title("title")
.snippet("snippet" )
.icon(image));


}

class GetVehicleValue extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}

@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();

// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);

if (jsonStr != null) {
try {
JSONArray jr = new JSONArray(jsonStr);

vehicleHolder = new ArrayList<>();
for (int i = 0; i < jsonStr.length(); i++) {
JSONObject jb = (JSONObject) jr.getJSONObject(i);
plate_num = jb.getString("plate_num");
gps_num = jb.getString("gps_num");
location = jb.getString("location");
date = jb.getString("date");
time = jb.getString("time");
lat = jb.getString("lat");
lng = jb.getString("lng");
engine = jb.getString("engine");
remarks = jb.getString("remarks");

vehicleHolder.add(new VehicleHolder(lat, lng));

}

} catch (final JSONException e) {
e.printStackTrace();
}
} else {
Log.d("JSON:", "is null");
}

return null;
}

Answer Source

Your location model class:

public class LocationHolder {

    private String longitude,latitude,location,direction;

    public LocationHolder(String longitude, String latitude, String location, String direction) {
        this.longitude = longitude;
        this.latitude = latitude;
        this.location = location;
        this.direction = direction;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }
}

Parsing :

ArrayList<LocationHolder>list_location=new ArrayList<>();
for (int i = 0; i < contacts.length(); i++) {
    JSONObject c = contacts.getJSONObject(i);
    String account = c.getString("account");
    String trxdate = c.getString("trxdate");
    String trxtime = c.getString("trxtime");
    String longitude = c.getString("long");
    String latitude = c.getString("lat");
    String location = c.getString("location");
    String direction = c.getString("direction");
    String compass = c.getString("compass");
    String id = c.getString("id");
    String remarks = c.getString("remarks");
    String status = c.getString("status");
    String kmrun = c.getString("kmrun");
    String speed = c.getString("speed");
    String totalkm = c.getString("totalkm");
    String engine = c.getString("engine");
    String plateno = c.getString("plateno");    

    list_location.add(new LocationHolder(longitude,latitude,location,direction,))
}

button click

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        for(int i=0;i<list_location.length();i++)
        {
            createMarker(list_location.get(i).getLatitude(),list_location.get(i).getLongitude(),list_location.get(i).getLocation());
        }
});

createMarker Function:

private void createMarker(String latitude, String longitude,String snippet) {

    BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.map_pin);
    Double lat = Double.parseDouble(latitude);
    Double Longitude = Double.parseDouble(longitude);

    googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(lat, Longitude))
            .anchor(0.5f, 0.5f)
            .title(title)
            .snippet(snippet)
            .icon(icon));

    googleMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());

    googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {

            for (int i = 0; i < locationList.size(); i++) {
                  Log.d("TAG","getLatitude:"+list_location.get(i).getLatitude()+" getLongitude:"+list_location.get(i).getLongitude());
                if (marker.getSnippet().equals(list_location.get(i).getLocation())) {
                  Log.d("TAG","Selected Marker");
                }
            }
        }
    });
}

MarkerInfoWindowAdapter:Add your custom window info UI

  public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

    public MarkerInfoWindowAdapter() {
    }

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

    @Override
    public View getInfoContents(final Marker marker) {
       View v = getLayoutInflater().inflate(R.layout.custom_mapview, null);

        TextView markerLabel = (TextView) v.findViewById(R.id.tv_title);
        markerLabel.setText(marker.getTitle());

        return v;
    }
}

MyFragment

GoogleMap googleMap;

class MyFragment extends Fragment implements OnMapReadyCallback {

    @Override
    public void onMapReady(GoogleMap map) {
        googleMap = map;
        setUpMap();
    }

    /*set up map*/
    private void setUpMap() {
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.setTrafficEnabled(true);
        googleMap.setIndoorEnabled(true);
        googleMap.setBuildingsEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(0.0, 0.0)).zoom(15).build();
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        //set marker here
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download