I made a lot of research on this topic but couldn't find an appropriate solution.
I simply have an api which include school name and its latitude,longitude.
[
{
"id":1,
"name":"Little Angels Higher Secondary School",
"latitude":27.6514,
"longitude":85.3359
},
{
"id":6,
"name":"Baltimore Secondary School",
"latitude":27.6514,
"longitude":85.3359
}
]
I parsed this api data.Using GPStracker class I successfully included a marker on google map at my current location.Now I want to add a marker to all the school location in that google map so that I can know the nearest school to me once I open the google map.This is all what I did how ever it shows null pointer exception.
package com.example.user.educationhunt.fragment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.user.educationhunt.R;
import com.example.user.educationhunt.SchoolDetails;
import com.example.user.educationhunt.adapter.CustomListAdapter;
import com.example.user.educationhunt.pojos.AppController;
import com.example.user.educationhunt.pojos.FeeClass;
import com.example.user.educationhunt.pojos.GpsLocation;
import com.example.user.educationhunt.pojos.MySchool;
import com.example.user.educationhunt.pojos.OurSchool;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class NearMe extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
GpsLocation gpsLocation;
double longitude, latitude;
private ProgressDialog pDialog;
private RadioButton radioSexButton;
ArrayList al = new ArrayList();
MySchool mySchool;
Marker place;
LatLng current_location ;
private static final String TAG = NearMe.class.getSimpleName();
private static final String url = "http://www.myeducationhunt.com/api/v1/schools";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_near_me, container, false);
radioSexButton = (RadioButton) v.findViewById(R.id.radioSchool);
if (isConnected()) {
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
gpsLocation = new GpsLocation(getContext());
if (gpsLocation.canGetLocation()) {
longitude = gpsLocation.getLongitude();
latitude = gpsLocation.getLatitude();
Toast.makeText(getContext(), "latitude:" + latitude + "Longitude:" + longitude, Toast.LENGTH_LONG).show();
}
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Loading…");
pDialog.show();
JsonArrayRequest schoolRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
mySchool = new MySchool();
mySchool.setId(""+obj.getInt("id"));
mySchool.setName(""+obj.getString("name"));
mySchool.setLatitude(Double.parseDouble(""+obj.getDouble("latitude")));
mySchool.setLongitude(Double.parseDouble(""+obj.getDouble("longitude")));
al.add(mySchool);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(schoolRequest);
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
LatLng schoollatlng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(schoollatlng).title("MyLocation"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(10).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
LatLng latlng = new LatLng(mySchool.getLatitude(), mySchool.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latlng).title(mySchool.getName()));
CameraPosition cameraPosition1 = new CameraPosition.Builder().target(latlng).zoom(10).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition1));
}
});
} else {
Toast.makeText(getContext(), "Please check your internet connection", Toast.LENGTH_LONG).show();
}
return v;
}
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
Is there any one to help me?Please Help.Thanks in advance
This is MySchool class
package com.example.user.educationhunt.pojos;
/**
* Created by user on 12/28/2016.
*/
public class MySchool {
String id;
String name;
double latitude;
double longitude;
public String getId() {
return id;
}
public String getName() {
return name;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public void setId(String id) {
this.id = id;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public void setName(String name) {
this.name = name;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
}
This is my error log
FATAL EXCEPTION: main
Process: com.example.user.educationhunt, PID: 20472
java.lang.NullPointerException: Attempt to invoke virtual method 'double com.example.user.educationhunt.pojos.MySchool.getLatitude()' on a null object reference
at com.example.user.educationhunt.fragment.NearMe$3.onMapReady(NearMe.java:159)
at com.google.android.gms.maps.MapView$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:387)
at zu.a(:com.google.android.gms.DynamiteModulesB:82)
at maps.ad.t$5.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
12-28 10:06:05.046 20472-21276/com.example.user.educationhunt I/qtaguid: Untagging socket 81
Your school marker should run after google complete initialized. Below are the code sample.
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
LatLng schoollatlng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(schoollatlng).title("MyLocation"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(10).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
drawSchoolMarker();
}
});
Create new method in the class
private void drawSchoolMarker(){
JsonArrayRequest schoolRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MySchool school = new MySchool();
school.setId(""+obj.getInt("id"));
school.setName(""+obj.getString("name"));
school.setLatitude(Double.parseDouble(""+obj.getDouble("latitude")));
school.setLongitude(Double.parseDouble(""+obj.getDouble("longitude")));
al.add(school);
} catch (JSONException e) {
e.printStackTrace();
}
}
//iterate from arraylist
for(MySchool school : al){
LatLng latlng = new LatLng(school.getLatitude(), school.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latlng).title(school.getName()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(schoolRequest);
}
I didn't test the code but it should work.
After reading all school locations do some thing like by using your Array List
Marker place;
LatLng current_location ;
for(int i = 0; i < al.size(); i++){
current_location = new LatLng(Double.parseDouble(al.get(i).getLatitude()),Double.parseDouble(al.get(i).getLongitude()));
place= map.addMarker(new MarkerOptions().position(current_location).title("school name here"));
}
You should get NullPointerException in the line:
LatLng latlng = new LatLng(ourSchool.latitude, ourSchool.longitude);
because ourSchool is pointing to Null. You have added all the ourSchool objects in the ArrayList "al" like : al.add(ourSchool)
now try to iterate from the ArrayList "al" after adding the data in the ArrayList.
Also your below code is running before the getting response from the url and your "ourSchool" not initialise till that time.
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
LatLng schoollatlng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(schoollatlng).title("MyLocation"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(10).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
LatLng latlng = new LatLng(ourSchool.latitude, ourSchool.longitude);
googleMap.addMarker(new MarkerOptions().position(latlng).title(ourSchool.schoolName));
CameraPosition cameraPosition1 = new CameraPosition.Builder().target(latlng).zoom(10).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition1));
}
});
OurSchool class:
class OurSchool{
String id;
String name;
double latitude;
double longitude;
public void setId(String id){
this.id=id;
}
public String getId(){
return id;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setLatitude(double latitude){
this.latitute=latitude;
}
public double getLatitude(){
return latitude;
}
public void setLongitude(String longitude){
this.longitude=longitude;
}
public double getLongitude(){
return longitude;
}
}
then set value in OurSchool class object like:
ourSchool.setId(""+obj.getInt("id"));
in place of
ourSchool.schoolId = obj.getInt("id");
same way set values for other also
Related
Address Dailoge This is an Fragment when I click on image another activity (Location Activity)start in which Google map open.
Here is code of Address Dailoge fragment
when map open i want show the Current Location of user and user select the location from map using map picker
when user select the Location i want to take the Addresses of the street zipcode,state,country set it to the form.
public class AddressDialog extends DialogFragment {
public interface AddressListener {
void address(Address address);
void editedAddress(Address locationModel, int index);
}
private static final String TAG = "AddressDialog";
#BindView(R.id.addresslineone)
FormAnimationView addresslineone;
private GoogleApiClient mClient;
#BindView(R.id.addresslinetwo)
FormAnimationView addresslinetwo;
#BindView(R.id.city)
FormAnimationView cityView;
#BindView(R.id.state)
FormAnimationView stateView;
#BindView(R.id.country)
FormAnimationView countryView;
private boolean isfromEdit;
#BindView(R.id.pincode)
FormAnimationView pincode;
#BindView(R.id.edit_spinner_1)
EditSpinner mEditSpinner1;
private Address address = new Address();
private AddressListener addressListener;
private int index;
#OnClick(R.id.closedialog)
public void closeClick() {
this.dismiss();
}
#BindView(R.id.searchmap)
ImageView openmap;
#OnClick(R.id.searchmap)
public void searchmapclick() {
startActivityForResult(new Intent(getActivity(), LocationActivity.class), 100);
}
#OnClick(R.id.addaddressimg)
public void addClick() {
if (addressListener != null && address != null) {
if (!TextUtils.isEmpty(mEditSpinner1.getText()) &&
!TextUtils.isEmpty(addresslineone.getText())
&& !TextUtils.isEmpty(addresslinetwo.getText())
&& !TextUtils.isEmpty(cityView.getText())
&& !TextUtils.isEmpty(stateView.getText())
&& !TextUtils.isEmpty(pincode.getText())
&& !TextUtils.isEmpty(countryView.getText())) {
//locationModel.setAddressType(mEditSpinner1.getText().toString());
//address.setCountry(addresslinetwo.getText().toString());
// address.setLocality();
//address.setLocality("");
address.setRegion(stateView.getText().toString());
address.setFormatted(addresslineone.getText().toString());
address.setFormatted(addresslinetwo.getText().toString());
address.setCountry(countryView.getText().toString());
address.setLocality(cityView.getText().toString());
// address.setState(stateView.getText().toString());
address.setPostalCode(pincode.getText().toString());
address.setStreetAddress(addresslineone.getText().toString());
address.setStreetAddress(addresslinetwo.getText().toString());
address.setType(mEditSpinner1.getText().toString());
// address.setRegion();
if (!isfromEdit) {
addressListener.address(address);
} else {
addressListener.editedAddress(address, address.getIndex());
}
this.dismiss();
} else {
Toast.makeText(getActivity(), "All fields are mandetory", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStart() {
super.onStart();
mClient.connect();
}
#Override
public void onStop() {
mClient.disconnect();
super.onStop();
}
// #Override
// public void onAttach(Context context) {
// super.onAttach(context);
// //addressListener = (AddressListener) context;
// }
public void setListener(AddressListener addressListener) {
this.addressListener = addressListener;
}
/* #NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final View view = View.inflate(getActivity(), R.layout.address_selection_view, null);
Dialog dialog = new Dialog(getActivity(), R.style.DialogFragment);
dialog.setContentView(view);
return dialog;
}*/
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
// getDialog().getWindow().getWindowStyle().gets;
View rootView = inflater.inflate(R.layout.address_selection_view, container, false);
// getDialog().setTitle("Simple Dialog");
ButterKnife.bind(this, rootView);
mClient = new GoogleApiClient
.Builder(getContext())
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
try {
Address locationModel = (Address) getArguments().get("data");
if (locationModel != null) {
// getAddressDetails(locationModel.getAddress());
address.setAddressId(locationModel.getAddressId());
address.setFormatted("");
address.setCountry(addresslinetwo.getText().toString());
address.setLocality("");
address.setRegion("");
address.setPostalCode(pincode.getText().toString());
address.setStreetAddress(addresslineone.getText().toString());
address.setStreetAddress(addresslinetwo.getText().toString());
addresslineone.setText(locationModel.getStreetAddress());
addresslinetwo.setText(locationModel.getStreetAddress());
/*addresslinetwo.setText(locationModel.getCountry());*/
pincode.setText(locationModel.getPostalCode());
mEditSpinner1.setText(locationModel.getType());
countryView.setText(locationModel.getCountry());
stateView.setText(locationModel.getRegion());
cityView.setText(locationModel.getLocality());
isfromEdit = true;
}
} catch (Exception e) {
}
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
addresslineone.setHintMessage("Address Line 1 (Street / landmark)");
addresslineone.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
addresslineone.setTintColor(Color.parseColor("#de3f5abd"));
addresslineone.setFontStyle("fonts/Helvetica.otf");
addresslinetwo.setHintMessage("Address Line 2 (City / Country)");
addresslinetwo.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
addresslinetwo.setTintColor(Color.parseColor("#de3f5abd"));
addresslinetwo.setFontStyle("fonts/Helvetica.otf");
pincode.setHintMessage("Post / Zip / Pin Code");
pincode.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
pincode.setFontStyle("fonts/Helvetica.otf");
pincode.setTintColor(Color.parseColor("#de3f5abd"));
stateView.setInputType(InputType.TYPE_CLASS_TEXT);
stateView.setHintMessage("State");
stateView.setTintColor(Color.parseColor("#de3f5abd"));
stateView.setFontStyle("fonts/Helvetica.otf");
countryView.setInputType(InputType.TYPE_CLASS_TEXT);
countryView.setHintMessage("Country");
countryView.setTintColor(Color.parseColor("#de3f5abd"));
countryView.setFontStyle("fonts/Helvetica.otf");
cityView.setInputType(InputType.TYPE_CLASS_TEXT);
cityView.setHintMessage("City");
cityView.setTintColor(Color.parseColor("#de3f5abd"));
cityView.setFontStyle("fonts/Helvetica.otf");
ListAdapter adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.edits_array_1));
mEditSpinner1.setAdapter(adapter);
}
public void getAddressDetails(String address) {
StringBuilder stringBuilder = new StringBuilder();
if (address != null) {
String[] addressSlice = address.toString().split(", ");
String country = addressSlice[addressSlice.length - 1];
if (country != null) {
addresslinetwo.setText(country);
countryView.setText(country);
}
stringBuilder.append("Country:" + country);
if (addressSlice.length > 1) {
String[] stateAndPostalCode = addressSlice[addressSlice.length - 2].split(" ");
if (stateAndPostalCode.length > 1) {
String postalCode = stateAndPostalCode[stateAndPostalCode.length - 1];
String state = "";
for (int i = 0; i < stateAndPostalCode.length - 1; i++) {
state += (i == 0 ? "" : " ") + stateAndPostalCode[i];
}
stringBuilder.append("PostalCode:" + postalCode);
stringBuilder.append("State:" + state);
if (postalCode != null) {
pincode.setText(postalCode);
}
if (state != null) {
stateView.setText("" + state);
// pincode.setText(pincode.getText() + "," + state);
}
} else {
String state = stateAndPostalCode[stateAndPostalCode.length - 1];
stringBuilder.append("State:" + state);
stateView.setText("" + state);
}
}
String city = null;
if (addressSlice.length > 2)
city = addressSlice[addressSlice.length - 3].toString();
if (city != null) {
cityView.setText("" + city);
// addresslinetwo.setText(addresslinetwo.getText() + "," + city);
stringBuilder.append("City:" + city);
}
String stAddress1 = "";
if (addressSlice.length == 4)
stAddress1 = addressSlice[0];
else if (addressSlice.length > 3) {
String stAddress2 = addressSlice[addressSlice.length - 4];
for (int i = 0; i < addressSlice.length - 4; i++) {
stAddress1 += (i == 0 ? "" : ", ") + addressSlice[i];
}
}
stringBuilder.append("Address1:" + stAddress1);
if (stAddress1 != null) {
addresslineone.setText(stAddress1);
// addresslineone.getText().replaceAll("null", "");
}
}
// if(place.getLatLng()!=null)
// {
// String latitude = "" + place.getLatLng().latitude;
// String longitude = "" + place.getLatLng().longitude;
// }
Log.e(TAG, "getAddressDetails: " + stringBuilder.toString());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Log.e(TAG, "onActivityResult: " + requestCode);
if (requestCode == 100) {
try {
if (data.getExtras() != null && data.getExtras().getSerializable("data") != null) {
LocationModel locationModel = (LocationModel) data.getExtras().getSerializable("data");
if (locationModel != null) {
// addresslineone.setText(locationModel.getLocationname());
getAddressDetails(locationModel.getAddress());
//latitude = String.valueOf(locationModel.getLatitude());
//longitude = String.valueOf(locationModel.getLongitude());
}
}
} catch (Exception e) {
}
}
}
}
Here is the code of Location Activity
Map
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.planfisheye.fisheye.BaseActivity;
import com.planfisheye.fisheye.R;
import com.planfisheye.fisheye.adapters.NearByGetLocationParser;
import com.planfisheye.fisheye.adapters.PlacesAutoCompleteAdapter;
import com.planfisheye.fisheye.adapters.PlacesModel;
import com.planfisheye.fisheye.helper.CustomDialog;
import com.planfisheye.fisheye.models.LocationModel;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by venkateshmurthy on 24/12/16.
*/
public class LocationActivity extends BaseActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, PlaceSelectionListener {
private static final String TAG = "LocationActivity";
MapView mapView;
GoogleMap map;
private GoogleApiClient mClient;
#BindView(R.id.autocompletesearch)
AutoCompleteTextView autoSearch;
private static final int REQUEST_SELECT_PLACE = 1000;
private LatLng latlangObj;
private String address;
private String locationname;
private CustomDialog mCustomDialog;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#OnClick(R.id.doneclick)
public void doneClick() {
if(latlangObj!=null) {
LocationModel locationModel=new LocationModel();
locationModel.setLatitude(latlangObj.latitude);
locationModel.setLongitude(latlangObj.longitude);
locationModel.setLocationname(locationname);
locationModel.setAddress(address);
Intent intent=new Intent();
intent.putExtra("data",locationModel);
setResult(13, intent);
finish();
}else {
finish();
}
overridePendingTransition(R.anim.enter, R.anim.exit);
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_select);
ButterKnife.bind(this);
mapView = (MapView) findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mCustomDialog=new CustomDialog(this);
// try {
// Intent intent = new PlaceAutocomplete.IntentBuilder
// (PlaceAutocomplete.MODE_OVERLAY)
// // .setBoundsBias(BOUNDS_MOUNTAIN_VIEW)
// .build(this);
// startActivityForResult(intent, REQUEST_SELECT_PLACE);
// } catch (GooglePlayServicesRepairableException |
// GooglePlayServicesNotAvailableException e) {
// e.printStackTrace();
// }
// PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
// getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
// autocompleteFragment.setOnPlaceSelectedListener(this);
// autocompleteFragment.setHint("Search a Location");
mClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.enableAutoManage(this, this)
.addApi(Places.PLACE_DETECTION_API)
.build();
mClient.connect();
autoSearch.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.autocomplete_list_item));
autoSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
autoSearch.setText("");
}
});
autoSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//CommonUtils.hideKeyBoard(getActivity());
mCustomDialog.show();
final PlacesModel hm = (PlacesModel) autoSearch.getAdapter().getItem(position);
Log.e("place_id", "" + hm.getPlaceid());
// placetext.setText("" + hm.getDescription());
//AIzaSyA9_CVo9IETbjjqqBHC1eEYesVsaMPflIk
String[] codeInfo =
TextUtils.split(hm.getDescription(), ",");
// getLatLng(hm.getPlaceid());
Places.GeoDataApi.getPlaceById(mClient, hm.getPlaceid())
.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
mCustomDialog.dismiss();
if (places.getStatus().isSuccess() && places.getCount() > 0) {
final Place myPlace = places.get(0);
//getAddressDetails(myPlace);
Log.e("name", "Place found: " + myPlace.getName() + "\t" + myPlace.getAddress()+"\t"+myPlace.getLatLng());
if(myPlace.getAddress()!=null) {
address = myPlace.getAddress().toString();
}
latlangObj= myPlace.getLatLng();
locationname=hm.getDescription();
Log.e("latitude:", "" + latlangObj.latitude);
Log.e("longitude:", "" + latlangObj.longitude);
Marker marker = map.addMarker(new MarkerOptions()
.position(new LatLng(latlangObj.latitude, latlangObj.longitude))
.title("" + hm.getDescription()));
marker.showInfoWindow();
marker.setDraggable(true);
map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
} else {
Log.e("place", "Place not found");
}
places.release();
}
});
autoSearch.setText(""+hm.getDescription());
autoSearch.setSelection(autoSearch.getText().length());
}
});
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
MapsInitializer.initialize(this);
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
mClient.disconnect();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.map = googleMap;
}
#Override
public void onPlaceSelected(Place place) {
}
#Override
public void onError(Status status) {
}
private class NearbyLatlngTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
GetLatLngTask parserTask = new GetLatLngTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class GetLatLngTask extends AsyncTask<String, Integer, List<HashMap<String, Double>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, Double>> doInBackground(String... jsonData) {
List<HashMap<String, Double>> places = null;
NearByGetLocationParser nearPlaceJsonParser = new NearByGetLocationParser();
try {
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = nearPlaceJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, Double>> list) {
// Clears all the existing markers
// mGoogleMap.clear();
if (list != null) {
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, Double> hmPlace = list.get(i);
// Getting latitude of the place
double lat = hmPlace.get("lat");
// Getting longitude of the place
double lng = hmPlace.get("lng");
Log.e("lat", "lat" + lat);
Log.e("long", "long" + lng);
Toast.LENGTH_SHORT).show();
}
}
}
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
//Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private void getLatLng(String placeID) {
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/details/json?placeid=" + placeID);
sb.append("&key=AIzaSyBiV3T00af_2jM0Vinlcws2Gc6K7ktVp38");
NearbyLatlngTask placesTask = new NearbyLatlngTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Check this,
map.setOnMapLongClickListener(new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
addMarker();
}
});
add this is addMarker method,
private void addMarker() {
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
googleMap.addMarker(marker);
}
I'm trying to display a google map inside a fragment.The location is plotted correctly inside map but when i press back after mapping the location it shows another fragment and again press back showing an inflate exception.
Note:-
I have used only one activity and all other pages are fragments.
The below given is the code snippet for fragment(for displaying gmap)
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map_container"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
logcat:-
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.integral.loqal, PID: 15338
android.view.InflateException: Binary XML file line #84: Binary XML file line #84: Error inflating class fragment
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.integral.loqal.Fragment.AddLocationFragment.onCreateView(AddLocationFragment.java:111)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.popFromBackStack(BackStackRecord.java:979)
at android.support.v4.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1670)
at android.support.v4.app.FragmentManagerImpl$2.run(FragmentManager.java:577)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #84: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.integral.loqal.Fragment.AddLocationFragment.onCreateView(AddLocationFragment.java:111)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.popFromBackStack(BackStackRecord.java:979)
at android.support.v4.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1670)
at android.support.v4.app.FragmentManagerImpl$2.run(FragmentManager.java:577)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #84: Duplicate id 0x7f0b0119, tag null, or parent id 0x7f0b00bb with another fragment for com.google.android.gms.maps.SupportMapFragment
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2293)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:186)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.integral.loqal.Fragment.AddLocationFragment.onCreateView(AddLocationFragment.java:111)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.popFromBackStack(BackStackRecord.java:979)
at android.support.v4.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1670)
at android.support.v4.app.FragmentManagerImpl$2.run(FragmentManager.java:577)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
java code:-
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.integral.loqal.CheckNetworkConnection;
import com.integral.loqal.Model.LocationItems;
import com.integral.loqal.PlaceDetailsJSONParser;
import com.integral.loqal.PlaceJSONParser;
import com.integral.loqal.R;
import com.integral.loqal.SessionManager;
import com.integral.loqal.Util.Utility;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
public class AddLocationFragment extends Fragment implements OnMapLongClickListener, OnMarkerDragListener {
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_google_map, container, false);
mapTextView = (TextView) v.findViewById(R.id.mapTextView);
doneTextView = (TextView) v.findViewById(R.id.doneTextView);
googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_container)).getMap();
googleMap.setOnMarkerDragListener(this);
googleMap.setOnMapLongClickListener(this);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
atvPlaces = (AutoCompleteTextView) v.findViewById(R.id.searchLoc);
atvPlaces.setThreshold(1);
atvPlaces.showDropDown();
latlong = latitude + "," + longitude;
LatLng latLng = new LatLng(latitude, longitude);
marker = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude)));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
backarrowImageView = (ImageView) v.findViewById(R.id.backArrowImageView);
Bundle bundle = this.getArguments();
int myInt = bundle.getInt("key", 0);
if (myInt != 0 && myInt == 1) {
mapTextView.setVisibility(View.INVISIBLE);
backarrowImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().popBackStack();
});
doneTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Boolean inet = new CheckNetworkConnection().isNetworkAvailable(getContext());
if (inet == true) {
if (atvPlaces.getText().toString().equals("")) {
Toast.makeText(getContext(), "Please choose a location", Toast.LENGTH_SHORT).show();
} else {
updateLocation();
utility.registerUserResponse(jsonObject, UserLocationSet_URL,
"UserLocationSet", getContext());
}
} else {
Toast.makeText(getContext(), "Check your internet connection", Toast.LENGTH_SHORT).show();
}
}
});
atvPlaces.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Creating a DownloadTask to download Google Places matching "s"
placesDownloadTask = new DownloadTask(PLACES);
// Getting url to the Google Places Autocomplete api
String url = getAutoCompleteUrl(s.toString());
// Start downloading Google Places
// This causes to execute doInBackground() of DownloadTask class
placesDownloadTask.execute(url);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
atvPlaces.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index,
long id) {
ListView lv = (ListView) arg0;
SimpleAdapter adapter = (SimpleAdapter) arg0.getAdapter();
HashMap<String, String> hm = (HashMap<String, String>) adapter.getItem(index);
// Creating a DownloadTask to download Places details of the selected place
placeDetailsDownloadTask = new DownloadTask(PLACES_DETAILS);
// Getting url to the Google Places details api
String url = getPlaceDetailsUrl(hm.get("reference"));
// Start downloading Google Place Details
// This causes to execute doInBackground() of DownloadTask class
placeDetailsDownloadTask.execute(url);
}
});
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_container)).getMap();
public String getAutoCompleteUrl(String place) {
// Obtain browser key from https://code.google.com/apis/console
String key = "key=";
// place to be be searched
String input = "input=" + place;
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input + "&" + types + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/" + output + "?" + parameters;
return url;
}
private String getPlaceDetailsUrl(String ref) {
// Obtain browser key from https://code.google.com/apis/console
String key = "key=";
// reference of place
String reference = "reference=" + ref;
Log.d("TAg", reference);
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = reference + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/details/" + output + "?" + parameters;
return url;
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
System.out.println(data);
String s[] = data.split(",");
String pl = s[0];
System.out.println(pl);
br.close();
} catch (Exception e) {
// Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
#Override
public void onMapLongClick(LatLng arg0) {
if (marker != null) {
marker.remove();
}
marker = googleMap.addMarker(new MarkerOptions()
.position(
new LatLng(arg0.latitude,
arg0.longitude))
.draggable(true).visible(true));
}
#Override
public void onMarkerDragStart(Marker arg0) {
}
#Override
public void onMarkerDrag(Marker arg0) {
}
#Override
public void onMarkerDragEnd(Marker arg0) {
LatLng dragPosition = arg0.getPosition();
latitude = dragPosition.latitude;
longitude = dragPosition.longitude;
dataloc = latitude + "," + longitude;
String name = getCompleteAddressString(latitude, longitude);
editor.putString("latitudeKey", Double.toString(latitude));
editor.putString("longitudeKey", Double.toString(longitude));
editor.putString("LocationName", name);
editor.commit();
latlong = latitude + "," + longitude;
Log.i("info", "on drag end :" + latitude + " dragLong :" + longitude);
Toast.makeText(getContext(), "Marker Dragged..!", Toast.LENGTH_SHORT).show();
}
private class DownloadTask extends AsyncTask<String, Void, String> {
private int downloadType = 0;
// Constructor
public DownloadTask(int type) {
this.downloadType = type;
}
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
switch (downloadType) {
case PLACES:
// Creating ParserTask for parsing Google Places
placesParserTask = new ParserTask(PLACES);
// Start parsing google places json data
// This causes to execute doInBackground() of ParserTask class
placesParserTask.execute(result);
break;
case PLACES_DETAILS:
// Creating ParserTask for parsing Google Places
placeDetailsParserTask = new ParserTask(PLACES_DETAILS);
// Starting Parsing the JSON string
// This causes to execute doInBackground() of ParserTask class
placeDetailsParserTask.execute(result);
}
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
int parserType = 0;
public ParserTask(int type) {
this.parserType = type;
}
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
JSONObject jObject;
List<HashMap<String, String>> list = null;
try {
jObject = new JSONObject(jsonData[0]);
switch (parserType) {
case PLACES:
list = placeJsonParser.parse(jObject);
break;
case PLACES_DETAILS:
PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
// Getting the parsed data as a List construct
list = placeDetailsJsonParser.parse(jObject);
System.out.println(list);
}
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return list;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
try {
switch (parserType) {
case PLACES:
String[] from = new String[]{"description"};
int[] to = new int[]{android.R.id.text1};
if (getActivity() != null) {
adapter = new SimpleAdapter(getActivity(), result, android.R.layout.simple_list_item_1, from, to);
atvPlaces.setAdapter(adapter);
}
break;
case PLACES_DETAILS:
HashMap<String, String> hm = result.get(0);
// Getting latitude from the parsed data
double newlatitude = Double.parseDouble(hm.get("lat"));
// Getting longitude from the parsed data
double newlongitude = Double.parseDouble(hm.get("lng"));
latlong = newlatitude + "," + newlongitude;
// Getting reference to the SupportMapFragment of the activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_container);
// Getting GoogleMap from SupportMapFragment
googleMap = fm.getMap();
LatLng point = new LatLng(newlatitude, newlongitude);
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(point);
CameraUpdate cameraZoom = CameraUpdateFactory.zoomBy(15);
dataloc = latitude + "," + longitude;
// Utility.locationChange = latlong;
System.out.println(atvPlaces.getText().toString());
String s = atvPlaces.getText().toString();
String p[] = s.split(",");
String pla = p[0];
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point, zoomLevel));
MarkerOptions options = new MarkerOptions();
options.position(point);
options.title("Position");
options.snippet("Latitude:" + newlatitude + ",Longitude:" + newlongitude);
if (marker != null)
marker.remove();
// Adding the marker in the Google Map
marker = googleMap.addMarker(options);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void onBackPressed() {
getFragmentManager().popBackStack();
}
#Override
public void onResume() {
super.onResume();
}
}
I dont know why it is showing the error.Can someone help me to find a solution?
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map_container"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Please checkout this link for GOOGLE MAP DOCUMENTATION
Activity Class
/**
* init map fragment and get map async task
*/
private void initMapFragment() {
AppUtils.showLog(TAG, "initMapFragment");
try {
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} catch (Exception ex) {
ex.printStackTrace();
}
}
XML File
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mapwithmarker.MapsMarkerActivity" />
I have the following code and basically I am wondering how I can use this location method distanceBetween() to find the objects in my .JSON file that are under 500km away. I tried to craft together an if statement and a distanceBetween usage but it doesn't recognize it and I know my syntax has some real problems. Is this the right way to be trying to do this? Any help or tips or code is greatly greatly appreciated!
package com.dredaydesigns.radiostationfinder;
import android.R;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.gson.JsonParser;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.IOException;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks {
// String HTTPRadioURL = "https://transition.fcc.gov/fcc-bin/fmq?state=&call=&city=&arn=&serv=FC&vac=3&freq=0.0&fre2=107.9&facid=&asrn=&class=&dkt=&list=0&dist=100&dlat2="
// + latitude + "&mlat2=&slat2=&NS=N&dlon2="
// + longitude +"&mlon2=&slon2=&EW=W&size=9";
public static final String TAG = MainActivity.class.getSimpleName();
private RadioData mRadioData;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
#Bind(R.id.longitudeLabel) TextView mLongitudeLabel;
#Bind(R.id.latitudeLabel) TextView mLatitudeLabel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_content);
ButterKnife.bind(this);
double latitude = 32;
double longitude = -96;
double latitudeStations;
double longitudeStations;
final RadioData[] mRadioData = new RadioData[1];
//String radioFinderURL = "http://data.fcc.gov/lpfmapi/rest/v1/lat/" + latitude + "/long/" + longitude + "?format=json&secondchannel=true";
//String HTTPRadioURL = "https://transition.fcc.gov/fcc-bin/fmq?state=&call=&city=&arn=&serv=FC&vac=3&freq=0.0&fre2=107.9&facid=&asrn=&class=&dkt=&list=0&dist=100&dlat2="
// + latitude + "&mlat2=&slat2=&NS=N&dlon2="
// + longitude +"&mlon2=&slon2=&EW=W&size=9";
String radioFinderURL = "http://dredaycreative.com/json/radioData.json";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(radioFinderURL)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.v(TAG,jsonData);
if (response.isSuccessful()) {
mRadioData[0] = getCurrentDetails(jsonData);
}
} catch (IOException e) {
Log.e(TAG, "Exception Caught: ", e);
}
catch(JSONException e){
Log.e(TAG, "Exception Caught:", e);
}
}
});
}
private RadioData getCurrentDetails(String jsonData) throws JSONException {
JSONObject radioData = new JSONObject(jsonData);
String callSign;
double latitudeStations;
double longitudeStations;
int frequency;
JSONArray jsonArray = radioData.getJSONArray("array");
for(int i =0; i<jsonArray.length(); i++){
callSign = radioData.getJSONObject(i+"")
.getJSONArray("array").getJSONObject(i).getString("FIELD1");
frequency = Integer.parseInt(radioData.getJSONObject(i + "")
.getJSONArray("array").getJSONObject(i).getString("FIELD2"));
longitudeStations = Double.parseDouble(radioData.getJSONObject(i+"")
.getJSONArray("array").getJSONObject(i).getString("FIELD20"));
latitudeStations = Double.parseDouble(radioData.getJSONObject(i+"")
.getJSONArray("array").getJSONObject(i).getString("FIELD24"));
Log.i(TAG, "From JSON: " + callSign + frequency + latitudeStations + longitudeStations);
if {
distanceBetween(double latitude, double longitude, double latitudeStations, double longitudeStations, float[] results) <100km
RadioData currently = new RadioData();
}
}
return new RadioData();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeLabel.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeLabel.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
#Override
public void onConnectionSuspended(int i) {
}
}
UPDATED CODER AFTER COMMENT AT 7:55PMCMT 8/17/15
Okay thank you for your help! I switched it up in this way am I getting warmer, ha?
private RadioData getCurrentDetails(String jsonData) throws JSONException {
JSONObject radioData = new JSONObject(jsonData);
static void distanceBetween;
String callSign;
double latitudeStations;
double longitudeStations;
int frequency;
private int mRadius = distanceBetween(double latitude, double longitude, double latitudeStations, double longitudeStations, float[] results)
callSign = radioData.getJSONObject(i + "")
.getJSONObject(i).getString("FIELD1");
frequency = Integer.parseInt(radioData.getJSONObject(i + "")
.getJSONObject(i).getString("FIELD2"));
longitudeStations = Double.parseDouble(radioData.getJSONObject(i + "")
.getJSONObject(i).getString("FIELD20"));
latitudeStations = Double.parseDouble(radioData.getJSONObject(i + "")
.getJSONObject(i).getString("FIELD24"));
Log.i(TAG, "From JSON: " + callSign + frequency + latitudeStations + longitudeStations);
if{
500 >= mRadius;
RadioData radioData = new RadioData();
}
}
return new RadioData();
}
I have an app which takes android map marker locations (lat/long) from mysql database. And user from my app can add markers too. The problem is that when user adds location of the new marker it does not appear on map. However the lat and long values appear in mysql database and if i reinstall the app it will show added location. Issue here seems to be that i have to refresh the map and i don't know how to do it in google maps v2. I found some answers that i should clear all markers and then load them again like this:
googleMap.clear();
But sadly it did not work. I found that in version one there was this method
map.invalidate();
Sadly in Google Maps v2 there is no such method. Has anyone have any idea how to refresh Google Maps v2 when i reactivate activity or if i press refresh button, any suggestion will be appreciated.
Update
Code:
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.wunderlist.slidinglayer.SlidingLayer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import app.AppController;
import util.Content;
public class MainActivity extends Activity {
private GoogleMap googleMap;
// json object response url
private String urlJsonObj = "alsodontneedthis.json";
// json array response url
private String urlJsonArry = "dontneedthis";
private static String TAG = MainActivity.class.getSimpleName();
// Progress dialog
private ProgressDialog pDialog;
Content content = new Content();
public static String valueEntered;
// temporary string to show the parsed response
private String jsonResponse;
private SlidingLayer mSlidingLayer;
private TextView swipeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.getUiSettings();
googleMap.getUiSettings().setZoomControlsEnabled(true);
bindViews();
initState();
mSlidingLayer.bringToFront();
redirect();
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
mSlidingLayer.openLayer(true);
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#SuppressLint("NewApi")
#Override
protected void onResume() {
super.onResume();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
/**
* View binding
*/
private void bindViews() {
mSlidingLayer = (SlidingLayer) findViewById(R.id.slidingLayer1);
// swipeText = (TextView) findViewById(R.id.swipeText);
}
/**
* Initializes the origin state of the layer
*/
private void initState() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
setupSlidingLayerPosition(prefs.getString("layer_location", "right"));
setupShadow(prefs.getBoolean("layer_has_shadow", false));
setupLayerOffset(prefs.getBoolean("layer_has_offset", false));
setupPreviewMode(prefs.getBoolean("preview_mode_enabled", false));
}
private void setupSlidingLayerPosition(String layerPosition) {
LayoutParams rlp = (LayoutParams) mSlidingLayer.getLayoutParams();
int textResource;
Drawable d;
// if (layerPosition.equals("right")) {
textResource = R.string.swipe_right_label;
d = getResources().getDrawable(R.drawable.container_rocket_right);
mSlidingLayer.setStickTo(SlidingLayer.STICK_TO_RIGHT);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
// swipeText.setCompoundDrawables(null, d, null, null);
// swipeText.setText(getResources().getString(textResource));
mSlidingLayer.setLayoutParams(rlp);
}
private void setupShadow(boolean enabled) {
if (enabled) {
mSlidingLayer.setShadowSizeRes(R.dimen.shadow_size);
mSlidingLayer.setShadowDrawable(R.drawable.sidebar_shadow);
} else {
mSlidingLayer.setShadowSize(0);
mSlidingLayer.setShadowDrawable(null);
}
}
private void setupLayerOffset(boolean enabled) {
int offsetDistance = enabled ? getResources().getDimensionPixelOffset(R.dimen.offset_distance) : 0;
mSlidingLayer.setOffsetDistance(offsetDistance);
}
private void setupPreviewMode(boolean enabled) {
int previewOffset = enabled ? getResources().getDimensionPixelOffset(R.dimen.preview_offset_distance) : -1;
mSlidingLayer.setPreviewOffsetDistance(previewOffset);
}
public void buttonClicked(View v) {
switch (v.getId()) {
// case R.id.buttonOpen:
// mSlidingLayer.openLayer(true);
// break;
case R.id.buttonClose:
mSlidingLayer.closeLayer(true);
break;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mSlidingLayer.isOpened()) {
mSlidingLayer.closeLayer(true);
return true;
}
default:
return super.onKeyDown(keyCode, event);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addNewEvent:
Intent intent = new Intent(this, AddEvent.class);
startActivity(intent);
;
}
return true;
}
private void redirect() {
//showpDialog();
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
Content content = new Content();
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("nosaukums");
String email = person.getString("nosaukums");
String relation = person.getString("nosaukums");
Double lat=person.getDouble("latCo");
Double lng=person.getDouble("longCo");
content.setName(name);
content.setPopulation(email);
content.setlat(lat);
content.setlng(lng);
content.setRelation(relation);
System.out.println("name="+content.getName()+content.getlat());
LatLng lt = new LatLng(content.getlat(), content.getlng());
content.setLatlng(lt);
//valueEntered=lt.toString();
System.out.println("address="+content.getLatlng());
/*String home = latlng.getLong("home");
String mobile = phone.getString("mobile");*/
System.out.println("relation="+content.getRelation());
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Population: " + email + "\n\n";
jsonResponse += "Latitude: " + lat + "\n\n";
jsonResponse += "Longitude: " + lng + "\n\n\n";
jsonResponse += "Relation" + relation +"\n\n\n";
if(content.getRelation().equals("son"))
{
googleMap.addMarker(new MarkerOptions()
.position(lt)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_son))
.snippet(email)
.title(content.getName())).showInfoWindow();
}
else
{
googleMap.addMarker(new MarkerOptions()
.position(lt)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_daughter))
.title(content.getName())).showInfoWindow();
}
CameraPosition cameraPosition = new CameraPosition.Builder().target(lt).zoom(15.0f).build();
CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
googleMap.moveCamera(cameraUpdate);
}
//txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
//hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
//hidepDialog();
}
});
// Adding request to request queue
//AppController.getInstance() == null;
AppController.getInstance().addToRequestQueue(req);
}
}
Since googleMap.appMarker() seems not to get called, you propaply catch an Exception when calling content.getRelation().equals("son").
I want show the maps of my places, based on a selection of area like business,favorites, etc.
I am using the following intent for search and display the result in the maps in Android
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps"));
startActivity(intent);
When I click the maps place as favorites it shows that place in my places.
How can I divide the places based on category in Android?
You should use the place api for getting the selection of area.
Step by step,
How to get the list of nearest place of a location.
Step 1 : Go to API Console for obtaining the Place API
https://code.google.com/apis/console/
and select on services tab
on the place service
now select API Access tab and get the API KEY
now you have a API key for getting place
Now in programming
*Step 2 * : first create a class named Place.java. This class is used to contain the property of place which are provided by Place api.
package com.android.code.GoogleMap.NearsetLandmark;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
public class Place {
private String id;
private String icon;
private String name;
private String vicinity;
private Double latitude;
private Double longitude;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVicinity() {
return vicinity;
}
public void setVicinity(String vicinity) {
this.vicinity = vicinity;
}
static Place jsonToPontoReferencia(JSONObject pontoReferencia) {
try {
Place result = new Place();
JSONObject geometry = (JSONObject) pontoReferencia.get("geometry");
JSONObject location = (JSONObject) geometry.get("location");
result.setLatitude((Double) location.get("lat"));
result.setLongitude((Double) location.get("lng"));
result.setIcon(pontoReferencia.getString("icon"));
result.setName(pontoReferencia.getString("name"));
result.setVicinity(pontoReferencia.getString("vicinity"));
result.setId(pontoReferencia.getString("id"));
return result;
} catch (JSONException ex) {
Logger.getLogger(Place.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
#Override
public String toString() {
return "Place{" + "id=" + id + ", icon=" + icon + ", name=" + name + ", latitude=" + latitude + ", longitude=" + longitude + '}';
}
}
Now create a class named PlacesService
package com.android.code.GoogleMap.NearsetLandmark;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class PlacesService {
private String API_KEY;
public PlacesService(String apikey) {
this.API_KEY = apikey;
}
public void setApiKey(String apikey) {
this.API_KEY = apikey;
}
public List<Place> findPlaces(double latitude, double longitude,String placeSpacification)
{
String urlString = makeUrl(latitude, longitude,placeSpacification);
try {
String json = getJSON(urlString);
System.out.println(json);
JSONObject object = new JSONObject(json);
JSONArray array = object.getJSONArray("results");
ArrayList<Place> arrayList = new ArrayList<Place>();
for (int i = 0; i < array.length(); i++) {
try {
Place place = Place.jsonToPontoReferencia((JSONObject) array.get(i));
Log.v("Places Services ", ""+place);
arrayList.add(place);
} catch (Exception e) {
}
}
return arrayList;
} catch (JSONException ex) {
Logger.getLogger(PlacesService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
//https://maps.googleapis.com/maps/api/place/search/json?location=28.632808,77.218276&radius=500&types=atm&sensor=false&key=your_api_key
private String makeUrl(double latitude, double longitude,String place) {
StringBuilder urlString = new StringBuilder("https://maps.googleapis.com/maps/api/place/search/json?");
if (place.equals("")) {
urlString.append("&location=");
urlString.append(Double.toString(latitude));
urlString.append(",");
urlString.append(Double.toString(longitude));
urlString.append("&radius=1000");
// urlString.append("&types="+place);
urlString.append("&sensor=false&key=" + API_KEY);
} else {
urlString.append("&location=");
urlString.append(Double.toString(latitude));
urlString.append(",");
urlString.append(Double.toString(longitude));
urlString.append("&radius=1000");
urlString.append("&types="+place);
urlString.append("&sensor=false&key=" + API_KEY);
}
return urlString.toString();
}
protected String getJSON(String url) {
return getUrlContents(url);
}
private String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8);
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
Now create a new Activity where you want to get the list of nearest places.
/**
*
*/
package com.android.code.GoogleMap.NearsetLandmark;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.code.R;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
/**
* #author dwivedi ji *
* */
public class CheckInActivity extends ListActivity {
private String[] placeName;
private String[] imageUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
new GetPlaces(this,getListView()).execute();
}
class GetPlaces extends AsyncTask<Void, Void, Void>{
Context context;
private ListView listView;
private ProgressDialog bar;
public GetPlaces(Context context, ListView listView) {
// TODO Auto-generated constructor stub
this.context = context;
this.listView = listView;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
bar.dismiss();
this.listView.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, placeName));
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
bar = new ProgressDialog(context);
bar.setIndeterminate(true);
bar.setTitle("Loading");
bar.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
findNearLocation();
return null;
}
}
public void findNearLocation() {
PlacesService service = new PlacesService("past your key");
/*
Hear you should call the method find nearst place near to central park new delhi then we pass the lat and lang of central park. hear you can be pass you current location lat and lang.The third argument is used to set the specific place if you pass the atm the it will return the list of nearest atm list. if you want to get the every thing then you should be pass "" only
*/
List<Place> findPlaces = service.findPlaces(28.632808,77.218276,"atm");
// Hear third argument, we pass the atm for getting atm , if you pass the hospital then this method return list of hospital , If you pass nothing then it will return all landmark
placeName = new String[findPlaces.size()];
imageUrl = new String[findPlaces.size()];
for (int i = 0; i < findPlaces.size(); i++) {
Place placeDetail = findPlaces.get(i);
placeDetail.getIcon();
System.out.println( placeDetail.getName());
placeName[i] =placeDetail.getName();
imageUrl[i] =placeDetail.getIcon();
}
}
}