How to convert String values into LatLng() objects? - java

I have latlng values in String .I want to convert That String into LatLng objects. likeLatLng latlng = new LatLng(lat, lng);
This is my data :
String latlan ="
[[13.041695199971244, 77.61311285197735],
[13.042000923637021, 77.61313531547785],
[13.041830750574812, 77.61335827410221],
[13.041507062142946, 77.61269208043814]]
";
Thanks in advance

Parse your data as follows:
List<LatLng> coordinates = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(latlan);
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray latLong = jsonArray.getJSONArray(i);
double lat = latLong.getDouble(0);
double lon = latLong.getDouble(1);
coordinates.add(new LatLng(lat, lon));
}
} catch (JSONException e) {
e.printStackTrace();
}
System.err.println(Arrays.toString(coordinates.toArray()));
for (LatLng latLng : coordinates) {
//use the coordinates.
}

I would just use a bunch of splits and replaceAlls to divide it up and then use the LatLan constructor in a foreach loop.
String latlng = "[[13.041695199971244, 77.61311285197735], [13.042000923637021, 77.61313531547785], [13.041830750574812, 77.61335827410221], [13.041507062142946, 77.61269208043814]]";
String[] latlngParts = latlng.split("\\], \\[");
for (String ll: latlngParts) {
String llReplaced = ll.replaceAll("\\[", "").replaceAll("\\]", "");
String[] llReplacedParts = llReplaced.split(", ");
LatLng latlngObj = new LatLng(llReplacedParts[0], llReplacedParts[1]);
// Then add latlngObj to some collection of LatLng objects
}

private void doConvertToLatLan(){
String latlan = "[[13.041695199971244, 77.61311285197735], [13.042000923637021, 77.61313531547785], [13.041830750574812, 77.61335827410221], [13.041507062142946, 77.61269208043814]]";
latlan = latlan.replace("[[","[");
latlan = latlan.replace("]]","]");
latlan = latlan.replace("[","");
latlan = latlan.replace("],","#");
String[] latlanDParts = latlan.split("#");
ArrayList<LatLan> data = new ArrayList<>();
for (String value: latlanDParts) {
String[] llReplacedParts = value.split(",");
data.add(new LatLan(llReplacedParts[0], llReplacedParts[1]));
}
Log.d("Data",data.toString());
}
private class LatLan{
private String lat,lan;
public LatLan(String lat, String lan) {
this.lat = lat;
this.lan = lan;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLan() {
return lan;
}
public void setLan(String lan) {
this.lan = lan;
}
};
I hope this will helpful!

Related

create itinary google maps android

After using gps for geolocalization, i want to create an line to show the itinary between two points. I know i need to use the polyline but after the JSON parsing, I don't know how to use the polyline options and I don't know how to use the part of Json named "steps". For the Http conection, i use the Volley Library. This my code:
public void geoLocate(View view){
String start = start_address.getText().toString();
String destination = destination_address.getText().toString();
Geocoder gc = new Geocoder(getActivity());
try {
List<android.location.Address> list = gc.getFromLocationName(start,1);
final Address adress1 = list.get(0);
String start_adress = adress1.getLocality();
double lat_start = adress1.getLatitude();
double lng_start = adress1.getLongitude();
list = gc.getFromLocationName(destination,1);
Address adress2 = list.get(0);
String destination_adress = adress2.getLocality();
double lat_destination = adress2.getLatitude();
double lng_destination = adress2.getLongitude();
if (start_marker != null || destination_marker != null){
start_marker.remove();
destination_marker.remove();
}
options_start = new MarkerOptions()
.title(start_adress)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.position(new LatLng(lat_start, lng_start));
start_marker = mGoogleMap.addMarker(options_start);
options_destination = new MarkerOptions()
.title(destination_adress)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.position(new LatLng(lat_destination, lng_destination));
destination_marker = mGoogleMap.addMarker(options_destination);
reservation.setClickable(true);
reservation.setEnabled(true);
reservation.setTextColor(getResources().getColor(R.color.white));
reservation.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
if(reservation.isClickable()) {
reservation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(start_marker.getPosition());
builder.include(destination_marker.getPosition());
LatLngBounds bounds = builder.build();
final StringBuilder url = new StringBuilder("http://maps.googleapis.com/maps/api/directions/json?sensor=false&language=fr");
url.append("&origin=");
url.append(start.replace(" ", "+"));
url.append("&destination=");
url.append(destination.replace(" ", "+"));
final Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
String status = jsonResponse.getString("status");
if (status.equals("OK")){
JSONArray parentArray = jsonResponse.getJSONArray("routes");
JSONObject routes = parentArray.getJSONObject(0);
if(routes != null){
JSONArray legsArray = routes.getJSONArray("legs");
JSONObject legsObject = legsArray.getJSONObject(0);
if (legsObject != null){
JSONObject distance = legsObject.getJSONObject("distance");
if (distance != null){
String distanceText = distance.getString("text");
distance_matrix.append(" "+distanceText);
}
JSONArray stepsArray = legsObject.getJSONArray("steps");
JSONObject stepsObject = stepsArray.getJSONObject(0);
if (stepsObject != null){
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
ItineraireRequest itineraireRequest = new ItineraireRequest(url.toString(), responseListener);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(itineraireRequest);
int padding = 125; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mGoogleMap.animateCamera(cu);
} catch (IOException e) {
e.printStackTrace();
}
}
Can you give a solution adapted to my code to make that, please?
I think this could help, the "getDocument()" do all the work
#Override
public void onMapReady(GoogleMap googleMap) {
GMapV2Direction md = new GMapV2Direction();
Document doc = md.getDocument(formatAddress(ORIGIN_TEXT, formatAddress(DESTINATION_TEXT, MODE, getApplicationContext());
if (doc != null) {
int duration = md.getDurationValue(doc);
if (duration > 0) {
try {
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(9).color(R.color.splash_blue).geodesic(true);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
AccessLocationActivity.this.mMap.addPolyline(rectLine);
} catch (Exception e) {
e.printStackTrace();
}
}
UPDATED
try this
public void geoLocate(View view){
String start = start_address.getText().toString();
String destination = destination_address.getText().toString();
Geocoder gc = new Geocoder(getActivity());
try {
List<android.location.Address> list = gc.getFromLocationName(start,1);
final Address adress1 = list.get(0);
String start_adress = adress1.getLocality();
double lat_start = adress1.getLatitude();
double lng_start = adress1.getLongitude();
list = gc.getFromLocationName(destination,1);
Address adress2 = list.get(0);
String destination_adress = adress2.getLocality();
double lat_destination = adress2.getLatitude();
double lng_destination = adress2.getLongitude();
if (start_marker != null || destination_marker != null){
start_marker.remove();
destination_marker.remove();
}
options_start = new MarkerOptions()
.title(start_adress)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.position(new LatLng(lat_start, lng_start));
start_marker = mGoogleMap.addMarker(options_start);
options_destination = new MarkerOptions()
.title(destination_adress)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.position(new LatLng(lat_destination, lng_destination));
destination_marker = mGoogleMap.addMarker(options_destination);
reservation.setClickable(true);
reservation.setEnabled(true);
reservation.setTextColor(getResources().getColor(R.color.white));
reservation.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
if(reservation.isClickable()) {
reservation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(start_marker.getPosition());
builder.include(destination_marker.getPosition());
LatLngBounds bounds = builder.build();
final StringBuilder url = new StringBuilder("http://maps.googleapis.com/maps/api/directions/json?sensor=false&language=fr");
url.append("&origin=");
url.append(start.replace(" ", "+"));
url.append("&destination=");
url.append(destination.replace(" ", "+"));
GMapV2Direction md = new GMapV2Direction();
Document doc = md.getDocument(formatAddress(start), formatAddress(destination), GMapV2Direction.MODE_DRIVING, getApplicationContext());
if (doc != null) {
int duration = md.getDurationValue(doc);
if (duration > 0) {
try {
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(9).color(R.color.colorPrimary).geodesic(true);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
mGoogleMap.addPolyline(rectLine);
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
This is a great wrapper on top of the Google DirectionsAPI if you are willing to give it a shot.
More detailed explanation here.

Google Maps, need to display country in TextView

i'm new to google maps and need to display the users country in a textView.
At the moment my app is displaying Latitude, Longitude and address..now I need the Country.
I have declared the following:
private LocationManager locationManager;
private Location myLocation;
And under OnCreate
lblAddress = (TextView) findViewById(R.id.tvAddress);
To get the Address I used;
private String getCompleteAddressString(double LATITUDE, double LONGITUDE, int x)
{
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null)
{
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++)
{
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
}
}
catch (Exception e)
{
lblAddress.setText("Your address cannot be determined");
}
return strAdd;
}
Now how do I get the country in the same way?
You already have the Address, you can just call the getCountryName() method on it.
What I would do is create a POJO class so that you can return both the Address and Country from the method:
class MyLocation {
public String address;
public String country;
}
Then, make your method call return an instance of MyLocation, and populate both the Address and the Country before returning:
private MyLocation getCompleteAddressString(double LATITUDE, double LONGITUDE, int x)
{
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
MyLocation myLocation = new MyLocation(); //added
try
{
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null)
{
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
myLocation.country = returnedAddress.getCountryName(); //added
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++)
{
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
myLocation.address = strAdd; //added
}
}
catch (Exception e)
{
lblAddress.setText("Your address cannot be determined");
}
return myLocation; //modified
}
Be sure to do null checks on the return values.
MyLocation loc = getCompleteAddressString(lat, lon, x);
if (loc.address != null) {
//use to populate Address TextView
}
if (loc.country != null) {
//use to populate Country TextView
}

Problems while displaying path between two points in google maps

This problem may sound a little weird, but whenever I run the app it crashes and when I change the name of LatLang variable in the function private LatLng getCurrentLocation(), It starts working. But when I change anything(even in any other file) it crashes and I have to keep changing the variable names to keep it running.
I am sure of the problem, it is something related to LatLang variable.
GetApproxTimeMaps.java
public class GetApproxTimeMaps extends FragmentActivity {
private static double destiLatitude;
private static double destiLongitude;
GoogleMap mMap;
GMapV2Direction md;
LatLng userLocation;
LatLng destination;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_approx_time_maps);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
userLocation = getCurrentLocation();
double lati = userLocation.latitude;
double longi = userLocation.longitude;
JSONObject jasonObject = getLocationInfo("Infosys");
boolean value = getLatLong(jasonObject);
System.out.println("value is: "+ value);
destination = new LatLng(destiLatitude, destiLongitude);
System.out.println("destination latitude :" + destiLatitude);
System.out.println("destination longitude :" + destiLongitude);
md = new GMapV2Direction();
mMap = ((SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
double toZoomLat = (destination.latitude + userLocation.latitude)/2;
double toZoomLon = (destination.longitude + userLocation.longitude)/2;
LatLng coordinates = new LatLng(toZoomLat, toZoomLon);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 12));
mMap.addMarker(new MarkerOptions().position(userLocation).title("Start"));
mMap.addMarker(new MarkerOptions().position(destination).title("End"));
Document doc = md.getDocument(userLocation, destination, GMapV2Direction.MODE_DRIVING);
int duration = md.getDurationValue(doc);
String distance = md.getDistanceText(doc);
String start_address = md.getStartAddress(doc);
String copy_right = md.getCopyRights(doc);
System.out.println(duration);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.BLUE);
for(int i = 0 ; i < directionPoint.size() ; i++) {
rectLine.add(directionPoint.get(i));
}
mMap.addPolyline(rectLine);
}
private LatLng getCurrentLocation(){
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userlocat = new LatLng(location.getLatitude(),location.getLongitude());
return userlocat;
}
public static JSONObject getLocationInfo(String address) {
StringBuilder stringBuilder = new StringBuilder();
try {
address = address.replaceAll(" ","%20");
HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
public static boolean getLatLong(JSONObject jsonObject) {
try {
destiLongitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
destiLatitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (JSONException e) {
return false;
}
return true;
}

How to return a class to a onPostExecute?

Update, please see below.
How do I return my class LocationData and my ArrayList listOfObjects to the onPostExecute()? I want to use it in my UI and right now it is in the background in an AsyncTask. Also I want to add markers with:
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lati, longi))
.title(name));
so that I can add each new location to the map after each loop.
Do I place the above in the onPostExecute after returning the LocationData class?
try {
String apples = endpoint.listContactInfo().execute().toString();
JSONObject jObject = new JSONObject(apples);
JSONArray jsonArr = jObject.getJSONArray("items");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj1 = jsonArr.getJSONObject(i);
// Storing each json item in variable
String id = jsonObj1.getString(TAG_ID);
String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
String phone1 = jsonObj1.getString(TAG_PHONE);
// test to see if made it to string
Log.d("YOUR_TAG", "First Name: " + nameFirst1 + " Last Name: "
+ nameLast1);
address = coder.getFromLocationName(streetAddress1, 5);
Address location1 = address.get(0);
// SET LAT LNG VALUES FOR MARKER POINT
lati = location1.getLatitude();
longi = location1.getLongitude();
Log.d("Location", "Location:" + lati + " " + longi);
class LocationData {
private double lat;
private double longitude;
private String name;
public LocationData(double lat, double longitude,
String name) {
this.lat = lat;
this.longitude = longitude;
this.name = name;
}
public void setLat(double lat) {
this.lat = lat;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLat() {
return lat;
}
public double getLongitude() {
return longitude;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
ArrayList<LocationData> listOfObjects = new ArrayList<LocationData>();
listOfObjects.add(new LocationData(lati, longi, nameFirst1));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (long) 0;
}
// WHAT DO I PUT HERE TO RETURN LocationData Class here
// ADD MARKER TO MAP UI
protected void onPostExecute() {
// mMap.addMarker(new MarkerOptions()
// .position(new LatLng(lati, longi))
// .title("Hello world"));
This may seem elementary but I've created this method:
public ArrayList getLocationData() {
ArrayList<LocationData> listOfObjects = new ArrayList<LocationData>();
listOfObjects.add(new LocationData(lati, longi, nameFirst1));
return listOfObjects;
}
within my LocationData class. I then placed LocationData.getLocationData(); with the onPostExecute and I get the LocationData can't be resolved. The code together looks like this at the moment:
try {
String apples = endpoint.listContactInfo().execute().toString();
JSONObject jObject = new JSONObject(apples);
JSONArray jsonArr = jObject.getJSONArray("items");
for(int i =0 ; i<jsonArr.length() ;i++ ){
JSONObject jsonObj1 = jsonArr.getJSONObject(i);
// Storing each json item in variable
String id = jsonObj1.getString(TAG_ID);
final String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
String phone1 = jsonObj1.getString(TAG_PHONE);
//test to see if made it to string
Log.d("YOUR_TAG", "First Name: " + nameFirst1 + " Last Name: " + nameLast1);
address = coder.getFromLocationName(streetAddress1,5);
Address location1 = address.get(0);
// SET LAT LNG VALUES FOR MARKER POINT
lati = location1.getLatitude();
longi = location1.getLongitude();
Log.d("Location", "Location:" + lati + " " + longi);
class LocationData {
private double lat;
private double longitude;
private String name;
public LocationData(double lat, double longitude, String name) {
this.lat = lat;
this.longitude = longitude;
this.name = name;
}
public void setLat(double lat) {
this.lat = lat;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLat() {
return lat;
}
public double getLongitude() {
return longitude;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public ArrayList<LocationData> getLocationData() {
ArrayList<LocationData> listOfObjects = new ArrayList<LocationData>();
listOfObjects.add(new LocationData(lati, longi, nameFirst1));
return listOfObjects;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (long) 0;
}
//WHAT DO I PUT HERE TO RETURN LocationData Class here
// ADD MARKER TO MAP UI
protected void onPostExecute(Long result ) {
//CANT BE RESOLVED
LocationData.getLocationData();
//mMap.addMarker(new MarkerOptions()
//.position(new LatLng(lati, longi))
// .title("Hello world"));
Here are my changes based upon #Sustain recommendations. I seem to not be getting any map markers now. Anyone see anything?
public class FinderActivity extends Activity implements LocationListener {
GoogleMap mMap;
Location myLocation;
EditText length;
String lengthString;
LocationManager locationmanager;
double lati;
double longi;
String nameFirst1;
//Spinner s;
List<Address> address;
Geocoder coder = new Geocoder(this);
private static final String TAG_ID = "id";
private static final String TAG_FIRSTNAME = "nameFirst";
private static final String TAG_LASTNAME = "nameLast";
private static final String TAG_EMAIL = "emailAddress";
private static final String TAG_ADDRESS = "streetAddress";
private static final String TAG_STATE = "state";
private static final String TAG_PHONE = "phone";
JSONArray contacts = null;
private static class LocationData {
private double lat;
private double longitude;
private String name;
public LocationData(double lat, double longitude, String name) {
this.lat = lat;
this.longitude = longitude;
this.name = name;
}
public void setLat(double lat) {
this.lat = lat;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLat() {
return lat;
}
public double getLongitude() {
return longitude;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap!= null) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomBy(17));
}
LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria cr = new Criteria();
String provider = locationmanager.getBestProvider(cr, true);
Location location = locationmanager.getLastKnownLocation(provider);
locationmanager.requestLocationUpdates(provider, 20, 0, (LocationListener) this);
mMap.moveCamera(CameraUpdateFactory.newLatLng((new LatLng(location.getLatitude(), location.getLongitude()))));
new EndpointsTask().execute(getApplicationContext());
}
public class EndpointsTask extends AsyncTask<Context, LocationData, Long> {
private List<LocationData> locationList = new ArrayList<LocationData>();
public Long doInBackground(Context... contexts) {
Contactinfoendpoint.Builder endpointBuilder = new Contactinfoendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Contactinfoendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
try {
String apples = endpoint.listContactInfo().execute().toString();
JSONObject jObject = new JSONObject(apples);
JSONArray jsonArr = jObject.getJSONArray("items");
for(int i =0 ; i<jsonArr.length() ;i++ ){
JSONObject jsonObj1 = jsonArr.getJSONObject(i);
// Storing each json item in variable
String id = jsonObj1.getString(TAG_ID);
String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
String phone1 = jsonObj1.getString(TAG_PHONE);
//test to see if made it to string
Log.d("YOUR_TAG", "First Name: " + nameFirst1 + " Last Name: " + nameLast1);
address = coder.getFromLocationName(streetAddress1,5);
Address location1 = address.get(0);
// SET LAT LNG VALUES FOR MARKER POINT
lati = location1.getLatitude();
longi = location1.getLongitude();
Log.d("Location", "Location:" + lati + " " + longi);
LocationData data = new LocationData(lati, longi, nameFirst1);
locationList.add(data);
publishProgress(data);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (long) 0;
}
protected void onProgressUpdate(LocationData data) {
// Add Marker on Map using data. This is called by
// publishProgress(LocationData) on the UI Thread.
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lati, longi))
.title(nameFirst1));
Log.d("bananas", lati + longi + nameFirst1);
}
//WHAT DO I PUT HERE TO RETURN LocationData Class here
// ADD MARKER TO MAP UI
protected void onPostExecute() {
}
}
The class LocationData is defined inside an unreachable scope. Instead, define it in it's own .java file like so:
class LocationData {
// final Fields
// Constructor
// Getters
}
or as a private static class of your outermost class if you don't use it anywhere else.
Then for your subclass of AsyncTask you could have something like:
private class AsyncJsonTask extends AsyncTask<Param, LocationData, Void>
{
private List<LocationData> locationList = new ArrayList<LocationData>();
// ...
protected void doInBackground(Param) {
// ...
for (int i = 0; i < jsonArr.length(); i++) {
// Do your stuff with JSon Objects
// ...
// Instanciate a new LocationData and pass it as progress:
LocationData data = new LocationData(latitude, longitude, name);
locationList.add(data);
publishProgress(data);
}
}
protected void onProgressUpdate(LocationData data) {
// Add Marker on Map using data. This is called by
// publishProgress(LocationData) on the UI Thread.
mMap.addMarker(/* marker */);
}
protected void onPostExecute() {
// Assign outer class member field the value of the builded list
// for future reference.
mLocationList = locationList;
}
}
This way, you can publish each marker individually on the map before fetching the next one.
As a side note, you should investigate the meaning of static methods and fields; your call to LocationData.getLocationData() would not be valid.
onPostExecute runs in the UI thread. So any changes in the UX can be done here, in your case, adding markers to the map.
onPostExecute takes in the Result parameter returned from doInBackground().
You can learn more about AsyncTask from http://developer.android.com/reference/android/os/AsyncTask.html
It got a nice example as well.

Adding Marker to map api v2 in AsyncTask

EDIT!
Not sure what I was thinking, but you can't update the UI in a background thread. oops.
How would I pass the marker add to the UI?
EDIT!
I'm trying to add markers to my map with api v2. If I add the markers in the onCreate it will work fine. If I add markers in my EndpointsTask directly below where I get the address information and convert it to lat long values it will not add the marker points.
Here is the code to add the marker:
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lati, longi))
.title("Hello world"));
Works fine when I put in actual double values in the onCreate. Does not work at all even with double values in the endpointstask (see below). In case you are wondering I sent the lati longi values to the console and it prints the lat long ok.
public class FinderActivity extends Activity implements LocationListener {
GoogleMap mMap;
Location myLocation;
EditText length;
String lengthString;
LocationManager locationmanager;
//Spinner s;
List<Address> address;
Geocoder coder = new Geocoder(this);
private static final String TAG_ID = "id";
private static final String TAG_FIRSTNAME = "nameFirst";
private static final String TAG_LASTNAME = "nameLast";
private static final String TAG_EMAIL = "emailAddress";
private static final String TAG_ADDRESS = "streetAddress";
private static final String TAG_STATE = "state";
private static final String TAG_PHONE = "phone";
JSONArray contacts = null;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap!= null) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomBy(17));
}
LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria cr = new Criteria();
String provider = locationmanager.getBestProvider(cr, true);
Location location = locationmanager.getLastKnownLocation(provider);
locationmanager.requestLocationUpdates(provider, 20, 0, (LocationListener) this);
mMap.moveCamera(CameraUpdateFactory.newLatLng((new LatLng(location.getLatitude(), location.getLongitude()))));
//WORKS HERE
//mMap.addMarker(new MarkerOptions()
//.position(new LatLng(38.923546, -83.582954))
//.title("Hello world"));
new EndpointsTask().execute(getApplicationContext());
}
public class EndpointsTask extends AsyncTask<Context, Integer, Long> {
public Long doInBackground(Context... contexts) {
Contactinfoendpoint.Builder endpointBuilder = new Contactinfoendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Contactinfoendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
try {
String apples = endpoint.listContactInfo().execute().toString();
JSONObject jObject = new JSONObject(apples);
JSONArray jsonArr = jObject.getJSONArray("items");
for(int i =0 ; i<jsonArr.length() ;i++ ){
JSONObject jsonObj1 = jsonArr.getJSONObject(i);
// Storing each json item in variable
String id = jsonObj1.getString(TAG_ID);
String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
String phone1 = jsonObj1.getString(TAG_PHONE);
//test to see if made it to string
Log.d("YOUR_TAG", "First Name: " + nameFirst1 + " Last Name: " + nameLast1);
address = coder.getFromLocationName(streetAddress1,5);
if (address == null) {
return null;
}
Address location1 = address.get(0);
double lati = location1.getLatitude();
double longi = location1.getLongitude();
Log.d("Location", "Location:" + lati + " " + longi);
// DOESNT WORK HERE
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lati, longi))
.title("Hello world"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (long) 0;
}
There are several ways but the postExecute method can solve your problem look this: how to pass the result of asynctask onpostexecute method into the parent activity android
protected void onPostExecute(Long result) {
// you can call a method of your activity
// example you can generate a list of all
// your markers and passed as param of method
// to your activity.
}

Categories