I am working on an Android app that shows map markers on an Google Map.
I want to show some info from every marker when the user clicks on it.
Now, the markers are shown, but nothing happens when the user clicks on the marker.
Here is my code:
#Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
mGoogleMap.clear();
getMarkers();
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,14));
}
private void getMarkers() {
StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Response: ", response.toString());
try {
JSONObject jObj = new JSONObject(response);
String getObject = jObj.getString("wisata");
JSONArray jsonArray = new JSONArray(getObject);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
title = jsonObject.getString(TITLE);
latLng = new LatLng(Double.parseDouble(jsonObject.getString(LAT)), Double.parseDouble(jsonObject.getString(LNG)));
tipo = jsonObject.getString(TIPO);
Log.d("Response","Tipo ="+tipo);
// Menambah data marker untuk di tampilkan ke google map
addMarker(latLng, title,tipo);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.getMessage());
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}
private void addMarker(LatLng latlng, final String title, final String tipo_reporte) {
markerOptions.position(latlng);
if (tipo_reporte.equals("1")) {
Drawable dr = getResources().getDrawable(R.drawable.reten1);
Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 100, 100, true));
Bitmap icono = ((BitmapDrawable) d).getBitmap();
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icono));
markerOptions.snippet(title);
}
mGoogleMap.addMarker(markerOptions);
mGoogleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(getContext(), marker.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
What should I change to get marker info?
Try to replace
setOnInfoWindowClickListener(...)
with
setOnMarkerClickListener(...)
You can use markers with onClickListener.
Related
I need to show my 'Npc' markers on the map , but the npcList in onMapReady() is empty. How can i put the right way my Npcs from getNPC() npcList in onMapReady() npcList and then display the markers on map
my onMapReady():
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//zoom map camera
// Get LocationManager object
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = (locationManager).getBestProvider(criteria, true);
Location myLocation = (locationManager).getLastKnownLocation(provider);
// myLastLoc = myLocation;
if (myLocation != null) {
//latitude of location
double myLatitude = myLocation.getLatitude();
//longitude og location
double myLongitude = myLocation.getLongitude();
LatLng latLon = new LatLng(myLatitude, myLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLon, 17));
}
mGoogleMap.setMyLocationEnabled(true);//koumpi gia location
buildGoogleApiClient(); // mallon mpilia
// locationManager.requestLocationUpdates(provider,1000,1f,com.google.android.gms.location.LocationListener);
npcList = new ArrayList<Npc>();
getNPC();
for(Npc mynpc:npcList) {
if (!npcList.isEmpty()) {
LatLng loc = new LatLng(mynpc.getNpclat(), mynpc.getNpclng());
String name = mynpc.getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
} else {
Toast.makeText(getActivity().getApplicationContext(), "npcList is empty", Toast.LENGTH_LONG).show();
}
}
}
my getNPC():
private void getNPC() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_NPC_GET,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.i("GAME_TAG", "response caught");
boolean error = obj.getBoolean("error");
if (!error) {
Log.i("GAME_TAG", "response showing return no error");
//converting the string to json array object
JSONArray array = obj.getJSONArray("results");
Log.i("GAME_TAG", "response has " + array.length() + " npcs");
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting npc object from json array
JSONObject npc = array.getJSONObject(i);
//adding the npc to npc list
npcList.add(new Npc(
npc.getInt("npcid"),
npc.getInt("userid"),
npc.getString("npcname"),
npc.getString("npcwelcome"),
(float) npc.getLong("npclat"),
(float) npc.getLong("npclng")
));
Log.i("GAME_TAG", "now arraylist has " + npcList.size() + " npcs");
Npc mynpc = npcList.get(i);
LatLng loc = new LatLng(mynpc.getNpclat(), mynpc.getNpclng());
String name = mynpc.getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "npc name "+ name+" " +loc);
}
Log.i("GAME_TAG", "if this sentence showing and still no marker, lets try adding only one marker");
LatLng loc = new LatLng(npcList.get(0).getNpclat(), npcList.get(0).getNpclng());
String name = npcList.get(0).getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "if this sentence showing and with one marker, something wrong with the loop");
} else {
Log.i("GAME_TAG", "response showing return with error");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestHandler.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
my Npc class:
package com.example.game1;
public class Npc {
private int npcid;
private int userid;
private String npcname;
private String npcwelcome;
private float npclat;
private float npclng;
public Npc(int npcid,int userid,String npcname,String npcwelcome,float npclat,float npclng){
this.npcid = npcid;
this.userid = userid;
this.npcname = npcname;
this.npcwelcome = npcwelcome;
this.npclat = npclat;
this.npclng = npclng;
}
public int getNpcid() {
return npcid;
}
public int getUserid() {
return userid;
}
public String getNpcname() {
return npcname;
}
public String getNpcwelcome() {
return npcwelcome;
}
public float getNpclat() {
return npclat;
}
public float getNpclng() {
return npclng;
}
}
im retrieving the right values from db as you can see in image bellow
image
please help me im stuck
try this, move your looping for adding marker in response after adding to your arraylist
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//zoom map camera
// Get LocationManager object
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = (locationManager).getBestProvider(criteria, true);
Location myLocation = (locationManager).getLastKnownLocation(provider);
// myLastLoc = myLocation;
if (myLocation != null) {
//latitude of location
double myLatitude = myLocation.getLatitude();
//longitude og location
double myLongitude = myLocation.getLongitude();
LatLng latLon = new LatLng(myLatitude, myLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLon, 17));
}
mGoogleMap.setMyLocationEnabled(true);//koumpi gia location
buildGoogleApiClient(); // mallon mpilia
// locationManager.requestLocationUpdates(provider,1000,1f,com.google.android.gms.location.LocationListener);
npcList = new ArrayList<Npc>();
getNPC();
}
your getnpc()
private void getNPC() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_NPC_GET,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.i("GAME_TAG", "response caught");
boolean error = obj.getBoolean("error");
if (!error) {
Log.i("GAME_TAG", "response showing return no error");
//converting the string to json array object
JSONArray array = obj.getJSONArray("results");
Log.i("GAME_TAG", "response has " + array.length() + " npcs");
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting npc object from json array
JSONObject npc = array.getJSONObject(i);
//adding the npc to npc list
npcList.add(new Npc(
npc.getInt("npcid"),
npc.getInt("userid"),
npc.getString("npcname"),
npc.getString("npcwelcome"),
npc.getLong("npclat"),
npc.getLong("npclng")
));
}
Log.i("GAME_TAG", "now arraylist has " + npcList.size() + " npcs");
for (Npc mynpc : npcList) {
LatLng loc = new LatLng(mynpc.getNpclat(), mynpc.getNpclng());
String name = mynpc.getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
}
Log.i("GAME_TAG", "if this sentence showing and still no marker, lets try adding only one marker");
LatLng loc = new LatLng(npcList.get(0).getNpclat(), npcList.get(0).getNpclng());
String name = npcList.get(0).getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "if this sentence showing and with one marker, something wrong with the loop");
} else {
Log.i("GAME_TAG", "response showing return with error");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestHandler.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
Hope it helps.
i did a few changes to getNPC() and now it works here is the code:
private void getNPC() {
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_NPC_GET,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.i("GAME_TAG", "response caught");
boolean error = obj.getBoolean("error");
if (!error) {
Log.i("GAME_TAG", "response showing return no error");
//converting the string to json array object
JSONArray array = obj.getJSONArray("results");
Log.i("GAME_TAG", "response has " + array.length() + " npcs");
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting npc object from json array
JSONObject npc = array.getJSONObject(i);
//adding the npc to npc list
npcList.add(new Npc(
npc.getInt("npcid"),
npc.getInt("userid"),
npc.getString("npcname"),
npc.getString("npcwelcome"),
(float) npc.getDouble("npclat"),
(float) npc.getDouble("npclng")
));
Log.i("GAME_TAG", "now arraylist has " + npcList.size() +
" npcs");
Npc mynpc = npcList.get(i);
LatLng loc = new LatLng(mynpc.getNpclat(),
mynpc.getNpclng());
String name = mynpc.getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "npc name "+ name+" " +loc);
}
Log.i("GAME_TAG", "if this sentence showing and still no
marker, lets try adding only one marker");
LatLng loc = new LatLng(npcList.get(0).getNpclat(),
npcList.get(0).getNpclng());
String name = npcList.get(0).getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "if this sentence showing and with one marker, something wrong with the loop");
} else {
Log.i("GAME_TAG", "response showing return with error");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestHandler.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
Hello i have this app that could detect users locations. In 1 activity I am displaying all the markers from mysql server using volley lirary and store in an array.
Now I want to get the data esp. the title of the marker and pass it to a String or a textview when it is clicked do something
here is my code:
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 20 seconds
if(locationsMarker != null){
locationsMarker.remove();
}
StringRequest stringRequest2 = new StringRequest(Request.Method.GET, locs_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array= new JSONArray(response);
JSONObject locations;
String from_lat_lng="";
for (int i = 0; i < array.length(); i++) {
locations = new JSONObject(array.get(i).toString());
String locs = locations.getString("current_loc");
Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(locs);
while(m.find()) {
from_lat_lng = m.group(1) ;
}
String[] gpsVal = from_lat_lng.split(",");
double lat = Double.parseDouble(gpsVal[0]);
double lon = Double.parseDouble(gpsVal[1]);
LatLng location_array = new LatLng(lat,lon);
Toast.makeText(ScanToHelp.this, "haha="+location_array.toString(), Toast.LENGTH_LONG).show();
points.add(location_array); //added
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(location_array);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
locationsMarker = mMap.addMarker(markerOptions);
// mMap.moveCamera(CameraUpdateFactory.newLatLng(location_array));
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location_array, 17.2f));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MySingleton.getInstance(ScanToHelp.this).addToRequestQueue(stringRequest2);
handler.postDelayed(this, 3000);
}
}, 100); //the time is in miliseconds
Thanks,
I am a newbie in android programming. I already retrieved LatLng from the database and the current location. The problem is i don't know how to draw path from the two marker. Thank you :) This is my Map Activity.
public class ModelMap extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
Button btnGo;
AutoCompleteTextView etSearch;
LatLng latLng;
GoogleMap mGoogleMap;
SupportMapFragment mFragment;
Marker currLocationMarker;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_model_map);
btnGo = (Button) findViewById(R.id.btnGo);
etSearch = (AutoCompleteTextView) findViewById(R.id.etSearch);
btnGo.setOnClickListener(this);
getMap();
}
#Override
public void onClick(View view) {
ArrayList<HashMap<String, String>> location = null;
String url = "http://enyatravel.com/maps/mapsdata/mapsModel.php";
try {
JSONArray data = new JSONArray(getHttpGet(url));
location = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("location_id", c.getString("location_id"));
map.put("latitude", c.getString("latitude"));
map.put("longitude", c.getString("longitude"));
map.put("name", c.getString("name"));
location.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
mGoogleMap.getUiSettings().setMapToolbarEnabled(false);
mGoogleMap.getUiSettings().setCompassEnabled(false);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
//zoom
Double latitude = Double.parseDouble(location.get(0).get("latitude").toString());
Double longitude = Double.parseDouble(location.get(0).get("longitude").toString());
LatLng coordinate = new LatLng(latitude, longitude);
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));
//marker
for (int i = 0; i < location.size(); i++) {
latitude = Double.parseDouble(location.get(i).get("latitude").toString());
longitude = Double.parseDouble(location.get(i).get("longitude").toString());
String name = location.get(i).get("name").toString();
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title(name);
mGoogleMap.addMarker(marker);
}
}
public void getMap() {
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googlemaps);
mFragment.getMapAsync(this);
}
public static String getHttpGet(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
try {
HttpResponse response = client.execute(httpget);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
mGoogleMap = googleMap;
mGoogleMap.setMyLocationEnabled(true);
buildGoogleApiClient();
mGoogleApiClient.connect();
}
protected synchronized void buildGoogleApiClient() {
Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
//place marker at current position
//mGoogleMap.clear();
latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icongps));
currLocationMarker = mGoogleMap.addMarker(markerOptions);
}
mLocationRequest = new LocationRequest();
// mLocationRequest.setInterval(5000); //5 seconds
// mLocationRequest.setFastestInterval(3000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this, "onConnectionSuspended", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this, "onConnectionFailed", Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
//place marker at current position
//mGoogleMap.clear();
if (currLocationMarker != null) {
currLocationMarker.remove();
}
latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icontao));
currLocationMarker = mGoogleMap.addMarker(markerOptions);
//Toast.makeText(this,"Location Changed",Toast.LENGTH_SHORT).show();
//zoom to current position:
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
//If you only need one location, unregister the listener
//LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
php:
$strSQL ="SELECT * FROM `loc_info` WHERE name= 'Saverde Coffee Shop'";
$objQuery = mysqli_query($objConnect, $strSQL);
// or die (mysqli_error());
$arrRows = array();
$arryItem = array();
while($arr = mysqli_fetch_array($objQuery)){
$arryItem["location_id"] = $arr["location_id"];
$arryItem["latitude"] = $arr["latitude"];
$arryItem["longitude"] = $arr["longitude"];
$arryItem["name"] = $arr["name"];
$arrRows[]= $arryItem;
}
echo json_encode($arrRows);
?>
If you got both points (Markers) where you want to draw the path then you have to draw PolliLines using your latlong. Below code will draw your path on map.
public void drawPath(String result) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#05b1fb"))//Google maps blue color
.geodesic(true)
);
}
catch (JSONException e) {
}
}
Just follow the link.
Answer : Draw path between two points using Google Maps Android API v2
You could use a Polyline. I have shared the links, the first one will give you a direct simple implementation. The other is to improve your understanding.
Polyline Implementation
Maps v2, Using Polyline
Hi friends I am working on the google maps where trying to add the marker dynamically using the JSON but I can able to add only two markers first and the last one i am using the for loop please help me out
Json Response
{"status":"Success","locations":[{"id":"2","hotel_name":"Igloo","address":"CMM Court Complex S.O","latitude":"12.9765944","longitude":"77.5992708"},{"id":"3","hotel_name":"The Park","address":"CMM Court Complex S.O","latitude":"12.9765944","longitude":"77.5992708"},{"id":"5","hotel_name":"Pai viceroy","address":"Kadugodi Extention SO","latitude":"12.9967012","longitude":"77.758197"},{"id":"8","hotel_name":"Prominere","address":"EPIP S.O","latitude":"12.9698066","longitude":"77.74996320000002"},{"id":"9","hotel_name":"Jaya","address":"Kadugodi Extention SO","latitude":"12.9967012","longitude":"77.758197"},{"id":"10","hotel_name":"Sitara","address":"Tavarekere S.O","latitude":"12.9342565","longitude":"77.60439930000007"},{"id":"11","hotel_name":"Loyalty","address":"Chandapura S.O","latitude":"12.8016","longitude":"77.7041"},{"id":"12","hotel_name":"Daspalla","address":"Ullalu Upanagar S.O","latitude":"1.370527","longitude":"103.83727999999996"}]}
My Code
private void mapsmethod() {
Display.showLoadingDialog(getActivity(), "Loading Locations");
String mapsurls = Jsonurl.url + "map_locations.php?city=" + Session.getcityname(getActivity());
Display.log(mapsurls);
JsonObjectRequest mapsreq = new JsonObjectRequest(Request.Method.GET, mapsurls, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray mapsarray = response.getJSONArray("locations");
// List<Marker> markers=new ArrayList<Marker>();
for (int i = 0; i < mapsarray.length(); i++) {
JSONObject mapsmarkerobj = mapsarray.getJSONObject(i);
/* MarkerOptions m = new MarkerOptions()
.title(mapsmarkerobj.optString("hotel_name"))
.position(new LatLng(mapsmarkerobj.optDouble("latitude"), mapsmarkerobj.optDouble("longitude")));
bottomap.addMarker(m);*/
/*long latitudemarker=mapsmarkerobj.getLong("latitude");
long longmarker=mapsmarkerobj.getLong("longitude");*/
/*Marker marker = bottomap.addMarker(new MarkerOptions().position(new LatLng(mapsmarkerobj.getLong("latitude"),mapsmarkerobj.getLong("longitude"))).title(mapsmarkerobj.getString("hotel_name")));
markers.add(marker);*/
}
// markers.size();
// Display.log(String.valueOf(markers.size()));
} catch (JSONException e) {
e.printStackTrace();
}
Display.hideLoadingDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Display.log(error.toString());
Display.hideLoadingDialog();
}
});
mapsreq.setRetryPolicy(new DefaultRetryPolicy(500000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(mapsreq);
}
How to add TAG to every marker and set the UniqueId on every marker.
Uniqueid's of every marker received from the server
Here is DoInBackgroung Code please help me
for (int i = 0; i < jsonarray.length(); i++) {
// ModelClass s = LoganSquare.parse(jsonarray.getJSONObject(i).toString(), ModelClass.class);
ModelClass modelClass = new Gson().fromJson(jsonarray.getJSONObject(i).toString(), ModelClass.class);
LatLng latLng = new LatLng(Double.parseDouble(modelClass.getLatitude()), Double.parseDouble(modelClass.getLongitude())); // Use your server's methods
latLngList.add(latLng);
Here is code to add marker
private void AddPointer() {
try {
if (marker != null) {
mMap.clear();
Toast.makeText(getApplicationContext(), "Remove", Toast.LENGTH_LONG).show();
}
for (LatLng object : latLngList)
marker = mMap.addMarker(new MarkerOptions().title("User Name").position(object).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4)));
System.out.println(marker.getPosition() + " Marker position.......");
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Error ", Toast.LENGTH_LONG).show();
// mMap.clear();
}
}
OnpostExecute code where i add the Marker that received from the server in this time i have two markers on server with its uniqueId's
protected void onPostExecute(Boolean result) {
// dialog.cancel();
// adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Receicve data from server", Toast.LENGTH_LONG).show();
if (result == false) {
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
AddPointer();
}
Here is Model Class
public class ModelClass {
#SerializedName("longi")
public String longitudeServer;
#SerializedName("lati")
public String latitudeServer;
#SerializedName("uniqueid")
public String uniqueidSserver;
public ModelClass(){
}
public String getLongitude(){
return longitudeServer;
}
public String getLatitude(){
return latitudeServer;
}
public String getUniqueId(){
return uniqueidSserver;
}
}
Try this you can set diffrent marker and give uniqueid or name
// Prepare Model Class like this way
public class LocationDetail
{
public String longitudeServer;
public String latitudeServer;
public String uniqueidSserver;
public String getLongitudeServer() {
return longitudeServer;
}
public void setLongitudeServer(String longitudeServer) {
this.longitudeServer = longitudeServer;
}
public String getLatitudeServer() {
return latitudeServer;
}
public void setLatitudeServer(String latitudeServer) {
this.latitudeServer = latitudeServer;
}
public String getUniqueidSserver() {
return uniqueidSserver;
}
public void setUniqueidSserver(String uniqueidSserver) {
this.uniqueidSserver = uniqueidSserver;
}
}
//Prepare the arraylist like this
try
{
LocationDetail modelclass;
JSONObject jsonObject = null;
ArrayList<LocationDetail> locationDetails = new ArrayList<>();
JSONArray jsonArray = ""; // initilise your server data
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
modelclass = new LocationDetail();
modelclass.setLongitudeServer(Double.parseDouble(jsonObject
.getString("Latitude").toString()));
modelclass.setLatitudeServer(Double.parseDouble(jsonObject
.getString("Longitude").toString()));
modelclass.setUniqueidSserver(jsonObject.getString(
"UniqueId").toString());
list.add(modelclass);
}
}
catch(JSONException e)
{
e.printStackTrace();
}
//Now pass above Arraylist to method
private void showMap(ArrayList<Reach_Us> list) {
double latitude = 0;
double longitude = 0;
try {
// Loading map
initilizeMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
// lets place some 10 random markers
for (int i = 0; i <= list.size(); i++) {
latitude = list.get(i).getLatitude();
longitude = list.get(i).getLongitude();
// Adding a marker
MarkerOptions marker = new MarkerOptions()
.position(
new LatLng(list.get(i).getLatitude(), list
.get(i).getLongitude()))
.title(i + ":"
+ list.get(i).getUniqueidSserver().toString());
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(list.get(i).getLatitude(), list
.get(i).getLongitude())).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Pravin i do like this.
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httpGet = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(data);
latLngList.clear();
try {
LocationDetail modelclass;
JSONObject jsonObject = null;
ArrayList<LocationDetail> locationDetails = new ArrayList<>();
// JSONArray jsonArray = ""; // initilise your server data
for (int i = 0; i < jsonarray.length(); i++) {
jsonObject = jsonarray.getJSONObject(i);
modelclass = new LocationDetail();
modelclass.setLongitudeServer(Double.parseDouble(jsonObject.getString("Latitude").toString()));
modelclass.setLatitudeServer(Double.parseDouble(jsonObject.getString("Longitude").toString()));
modelclass.setUniqueidSserver(jsonObject.getString("UniqueId").toString());
list.add(modelclass);
}
} catch (JSONException e) {
e.printStackTrace();
}
return true;
}
and also
private void showMap(ArrayList<LocationDetail> list) {
double latitude = 0;
double longitude = 0;
try {
// Loading map
initMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
mMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
mMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
mMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
mMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
mMap.getUiSettings().setZoomGesturesEnabled(true);
// lets place some 10 random markers
for (int i = 0; i <= list.size(); i++) {
latitude = list.get(i).getLatitudeServer();
longitude = list.get(i).getLongitudeServer();
// Adding a marker
MarkerOptions marker = new MarkerOptions()
.position(
new LatLng(list.get(i).getLatitudeServer(), list
.get(i).getLongitudeServer()))
.title(i + ":"
+ list.get(i).getUniqueidSserver().toString());
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
mMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(list.get(i).getLatitudeServer()), list.get(i).getLongitudeServer())).zoom(15).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
} catch (Exception e) {
e.printStackTrace();
}
}
And also in
public class LocationDetail
{
public double longitudeServer;
public double latitudeServer;
public String uniqueidSserver;
public double getLongitudeServer() {
return longitudeServer;
}
public void setLongitudeServer(double longitudeServer) {
this.longitudeServer = longitudeServer;
}
public double getLatitudeServer() {
return latitudeServer;
}
public void setLatitudeServer(double latitudeServer) {
this.latitudeServer = latitudeServer;
}
public String getUniqueidSserver() {
return uniqueidSserver;
}
public void setUniqueidSserver(String uniqueidSserver) {
this.uniqueidSserver = uniqueidSserver;
}
}
But error in this line
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(list.get(i).getLatitudeServer()), list.get(i).getLongitudeServer())).zoom(15).build(); it shows LatLnd Double Double cannot be applied to Double