Related
I'm trying to create a method for getting the altitude of a place from the website:
https://maps.googleapis.com/maps/api/elevation/json?locations=0,0 (where the 0,0 can be replaced with any coordinates).
However, I got a problem when getting the InputStream from the URL connection.
private double altitude(double lat, double longi) {
String elevation = "";
try {
URL alt = new URL("https://maps.googleapis.com/maps/api/elevation/json?locations="+lat+","+longi);
HttpURLConnection altFind = (HttpURLConnection) alt.openConnection();
altFind.setDoInput(true);
BufferedReader in = new BufferedReader(new InputStreamReader(altFind.getInputStream()));
String inputLine;
OUT:
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("elevation")) {
for (int i = 23; ; i++) {
if (inputLine.charAt(i) != ',') {
elevation = elevation + "" + inputLine.charAt(i);
} else {
break OUT;
}
}
}
}
return Double.parseDouble(elevation);
} catch (MalformedURLException e) {}
catch (IOException e) {}
return 0;
}
That is the method and I call it from here:
private TextView t;
private LocationManager locationManager;
private LocationListener listener;
double elev;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
Intent intent = getIntent();
String longlat = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
longlat = longlat.replaceAll(" ", "");
String [] longilati = longlat.split(",");
final double [] coord = new double[2];
coord[0] = Double.parseDouble(longilati[0]);
coord[1] = Double.parseDouble(longilati[1]);
t = (TextView) findViewById(R.id.textView);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
elev = altitude(coord[0], coord[1]);
} else {
Toast.makeText(this, "No connection available", Toast.LENGTH_LONG).show();
}
I've tried following similar questions to no avail.
You should perform Network Connections on Background Thread.
You can use Asynctask class and move altitude method inside doInBackground().
You can read more here:
https://developer.android.com/reference/android/os/AsyncTask.html
EDITED:
I found this class called JSONParser which I think this is what you need, check this out:
https://gist.github.com/dmnugent80/b2e22e5546c4b1c391ee
Copy and paste it into your project.
You can modify your altitude method by calling makeHttpRequest method from JSONParser class and passing all the parameters needed. If you do it right, then the method will return JSON object from the URL. For example:
private static final String URL = "https://maps.googleapis.com/maps/api/elevation/json";
private static final String METHOD = "GET"; // You can use POST either
private double altitude(double lat, double lng) {
double elevation = 0.0;
HashMap<String, String> params = new HashMap<>();
params.put("locations", lat + "," + lng);
// Here you can put another params if needed
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = jsonParser.makeHttpRequest(URL, METHOD, params);
if(jsonObject != null) {
Log.d(TAG, jsonObject.toString()); // Check if data has arrived safely?
try {
JSONArray results = jsonObject.getJSONArray("results");
JSONObject result = results.getJSONObject(0);
elevation = result.getDouble("elevation");
} catch (JSONException e) {
e.printStackTrace();
}
return elevation;
} else {
return -1;
}
}
Call altitude inside doInBackground and see the result.
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.
EDIT: Found the solution to my problem.
The json string output returned the wrong url for my local images.
i am barely new to android and struggle with asyncTask.
What i want is to get the corresponding image to a marker on a map.
every entry on this map has its own image which has to be loaded from server via json.
the image load works fine but i dont get the right workflow to get the image i need for one entry.
by now i have one solution to load an async task in a for-loop, but this cant be the right way because the app refuses to go on after 43 tasks and stops with
"ECONNECTION TIMEOUT"
so how can get the asynctask out of the loop?
hope anyone can help? thank you!
here is my code:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
JSONArray contentJson;
String contentId;
String imageJsonUrl;
String userId;
Bitmap bmp;
LatLng latLng;
Marker m;
HashMap<Marker, String> hashMap;
int k = 0;
// check value for Request check
final int MY_LOCATION_REQUEST_CODE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if(this.getIntent().getExtras() != null) {
try {
contentJson = new JSONArray(this.getIntent().getStringExtra("contentJson"));
// Log.v("TESTITEST", contentJson.toString());
} catch (JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_maps, menu);
return true;
}
public LatLng getLatLngPosition() {
return new LatLng(0, 0);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Ask for Permission. If granted show my Location
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_LOCATION_REQUEST_CODE);
} else {
// permission has been granted, continue as usual
mMap.setMyLocationEnabled(true);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
LatLng selectedLocation = place.getLatLng();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(selectedLocation, 10f));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("PlaceSelectorError", "An error occurred: " + status);
}
});
LatLng bonn = new LatLng(50.7323, 7.1847);
LatLng cologne = new LatLng(50.9333333, 6.95);
//mMap.addMarker(new MarkerOptions().position(bonn).title("Marker in Bonn"));
// hash map for saving content id with marker
hashMap = new HashMap<Marker, String>();
if(contentJson != null) {
if (this.getIntent().getStringExtra("contentId") == null) {
// show all contents of my friends
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
// Log.v("contentslength", String.valueOf(contents.length()));
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
//Log.v("eachcontent", eachcontent.toString());
JSONObject location = eachcontent.getJSONObject("Location");
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
Log.v("contentTitle", contentTitle);
//Log.v("m", m.toString());
//m = mMap.addMarker(new MarkerOptions().title(contentTitle).position(new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")))).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
}
}
} catch (JSONException e) {
Log.e("Exception", "unexpected JSON exception", e);
e.printStackTrace();
}
}
else {
// if we only want to see a specific content
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
JSONObject location = eachcontent.getJSONObject("Location");
if(eachcontent.getString("id").equals(this.getIntent().getStringExtra("contentId"))) {
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
// Log.v("LATLNG", contentId);
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
continue;
}
}
}
} catch (JSONException e) {
Log.e("LOGEDILOG", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 10f));
mMap.setOnMyLocationChangeListener(null);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = hashMap.get(marker);
Log.v("BITMAP", bmp.toString());
try {
Context context = getApplicationContext();
Intent mapIntent = new Intent(getApplicationContext(), contentDetailActivity.class);
mapIntent.putExtra("contentId", id);
mapIntent.putExtra("contentJson", contentJson.toString());
mapIntent.putExtra("userId", userId);
String filename = "profileImage.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
mapIntent.putExtra("image", filename);
startActivity(mapIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Marker[] addMarkers() {
return null;
}
/**
* lets you load Image from external source via url
*/
public class MapImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private final String LOG_TAG = MapImageLoadTask.class.getSimpleName();
String url, userId, contentId, title;
LatLng location;
BufferedReader reader = null;
public MapImageLoadTask(String url, String userId, String contentId, String title, LatLng location) {
this.url = url;
this.userId = userId;
this.contentId = contentId;
this.title = title;
this.location = location;
}
private String getImageUrlFromJson(String imageJson) throws JSONException {
JSONObject imageJsonOutput = new JSONObject(imageJson);
imageJsonUrl = imageJsonOutput.getString("imageUrl");
//Log.v(LOG_TAG, imageJsonUrl);
return imageJsonUrl;
}
#Override
protected Bitmap doInBackground(Void... params) {
String imageJson = null;
try {
URL urlConnection = new URL(url + userId);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (input == null) {
// Nothing to do.
//forecastJsonStr = null;
return null;
}
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
imageJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
String jsonUrl = getImageUrlFromJson(imageJson);
URL url = new URL(jsonUrl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
k +=1;
Log.v("COUNTER", String.valueOf(k));
m = mMap.addMarker(new MarkerOptions().title(title).position(location).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
hashMap.put(m, contentId);
}
}
}
Your problem maybe AsyncTask limitations. In android.os.AsyncTask.java you will see core size and blockingqueue size(128), should use counter for asynctask and debug it(Problem is, lots of async tasks or other).
AsyncTask.java
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
...}
Change Your Code Use Buffer(RequestData) And Use Only One Async Task. Update Market instance every publishProgress in onProgressUpdate
private GoogleMap mMap;
JSONArray contentJson;
String contentId;
String imageJsonUrl;
String userId;
Bitmap bmp;
LatLng latLng;
Marker m;
HashMap<Marker, String> hashMap;
int k = 0;
// check value for Request check
final int MY_LOCATION_REQUEST_CODE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if(this.getIntent().getExtras() != null) {
try {
contentJson = new JSONArray(this.getIntent().getStringExtra("contentJson"));
// Log.v("TESTITEST", contentJson.toString());
} catch (JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_maps, menu);
return true;
}
public LatLng getLatLngPosition() {
return new LatLng(0, 0);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Ask for Permission. If granted show my Location
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_LOCATION_REQUEST_CODE);
} else {
// permission has been granted, continue as usual
mMap.setMyLocationEnabled(true);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
LatLng selectedLocation = place.getLatLng();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(selectedLocation, 10f));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("PlaceSelectorError", "An error occurred: " + status);
}
});
LatLng bonn = new LatLng(50.7323, 7.1847);
LatLng cologne = new LatLng(50.9333333, 6.95);
//mMap.addMarker(new MarkerOptions().position(bonn).title("Marker in Bonn"));
// hash map for saving content id with marker
hashMap = new HashMap<Marker, String>();
if(contentJson != null) {
if (this.getIntent().getStringExtra("contentId") == null) {
// show all contents of my friends
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
// Log.v("contentslength", String.valueOf(contents.length()));
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
//Log.v("eachcontent", eachcontent.toString());
JSONObject location = eachcontent.getJSONObject("Location");
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
Log.v("contentTitle", contentTitle);
//Log.v("m", m.toString());
//m = mMap.addMarker(new MarkerOptions().title(contentTitle).position(new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")))).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
}
}
} catch (JSONException e) {
Log.e("Exception", "unexpected JSON exception", e);
e.printStackTrace();
}
}
else {
// if we only want to see a specific content
try {
List<RequestData> datas = new ArrayList<RequestData>();
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
JSONObject location = eachcontent.getJSONObject("Location");
if(eachcontent.getString("id").equals(this.getIntent().getStringExtra("contentId"))) {
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
// Log.v("LATLNG", contentId);
RequestData data = new RequestData();
data.url = "http://192.168.63.35:1234/rest_app_users/getImage/";
data.userId = userId;
data.contentId = contentId;
data.contentTitle = contentTitle;
data.latlng = latlng;
datas.add(data);
//new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
continue;
}
}
}
new MapImageLoadTask(datas).execute();
} catch (JSONException e) {
Log.e("LOGEDILOG", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 10f));
mMap.setOnMyLocationChangeListener(null);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = hashMap.get(marker);
Log.v("BITMAP", bmp.toString());
try {
Context context = getApplicationContext();
Intent mapIntent = new Intent(getApplicationContext(), contentDetailActivity.class);
mapIntent.putExtra("contentId", id);
mapIntent.putExtra("contentJson", contentJson.toString());
mapIntent.putExtra("userId", userId);
String filename = "profileImage.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
mapIntent.putExtra("image", filename);
startActivity(mapIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Marker[] addMarkers() {
return null;
}
/**
* lets you load Image from external source via url
*/
static class RequestData{
public String url;
public String userId;
public String contentId;
public String contentTitle;
public LatLng latLng;
public Bitmap bmp;
}
public class MapImageLoadTask extends AsyncTask<Void, RequestData, Void> {
private final String LOG_TAG = MapImageLoadTask.class.getSimpleName();
BufferedReader reader = null;
List<RequestData> dataSet;
public MapImageLoadTask(List<RequestData> dataSet) {
this.dataSet = dataSet;
}
private String getImageUrlFromJson(String imageJson) throws JSONException {
JSONObject imageJsonOutput = new JSONObject(imageJson);
imageJsonUrl = imageJsonOutput.getString("imageUrl");
//Log.v(LOG_TAG, imageJsonUrl);
return imageJsonUrl;
}
#Override
protected Bitmap doInBackground(Void... params) {
for(RequestData item : dataSet){
String imageJson = null;
try {
URL urlConnection = new URL(url + userId);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (input == null) {
// Nothing to do.
//forecastJsonStr = null;
return null;
}
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
imageJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
String jsonUrl = getImageUrlFromJson(imageJson);
URL url = new URL(jsonUrl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
//
item.bmp = bmp;
publishProgress(item);
}
catch(Exception e) {
e.printStackTrace();
}
}
return null;
}
protected void onPublishProgress(RequestData item){
k +=1;
Log.v("COUNTER", String.valueOf(k));
m = mMap.addMarker(new MarkerOptions().title(item.title).position(item.location).icon(BitmapDescriptorFactory.fromBitmap(item.bmp)));
hashMap.put(m, contentId);
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}
I am a newbie in android and here is my code, the problem is this code is not able to draw the path on the map.
This my main activity
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
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.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import org.w3c.dom.Document;
import java.util.ArrayList;
public class servicing extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
protected GoogleMap mMap;
String lang = "english";
String test = "test";
protected LocationManager locationManager;
Route route = new Route();
LatLng latLng1 = new LatLng(26.903291,75.792482);
LatLng latLng2 = new LatLng(26.907708,75.806044);
ArrayList<LatLng> points = new ArrayList<>(2);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_servicing);
//GMapV2Direction md = new GMapV2Direction();
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
/*Document doc = md.getDocument(latLng1, latLng2,
GMapV2Direction.MODE_DRIVING);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
Polyline polylin = mMap.addPolyline(rectLine);*/
points.add(latLng1);
points.add(latLng2);
route.drawRoute(mMap, this, points, true, lang, false);
Toast.makeText(getApplicationContext(),driverdata.extrastmt,Toast.LENGTH_LONG).show();
//route.drawRoute(mMap,this,latLng1,latLng2,lang);
}
#Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom((latLng1),15);
mMap.animateCamera(cameraUpdate);
//route.drawRoute(mMap, this, points, true, lang, false);
}
#Override
public void onProviderEnabled(String provider) {
(Toast.makeText(getApplication(), "Reconnecting", Toast.LENGTH_LONG)).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplication(),"Connection Failed! Check Network!",Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude", "status");
}
#Override
public void onLocationChanged(Location location) {
Log.d("Latitude", "status");
}
}
And this my route class
public class Route {
GoogleMap mMap;
Context context;
String lang;
static String LANGUAGE_SPANISH = "es";
static String LANGUAGE_ENGLISH = "en";
static String LANGUAGE_FRENCH = "fr";
static String LANGUAGE_GERMAN = "de";
static String LANGUAGE_CHINESE_SIMPLIFIED = "zh-CN";
static String LANGUAGE_CHINESE_TRADITIONAL = "zh-TW";
static String TRANSPORT_DRIVING = "driving";
static String TRANSPORT_WALKING = "walking";
static String TRANSPORT_BIKE = "bicycling";
static String TRANSPORT_TRANSIT = "transit";
public boolean drawRoute(GoogleMap map, Context c, ArrayList<LatLng> points, boolean withIndications, String language, boolean optimize)
{
mMap = map;
context = c;
lang = language;
if(points.size() == 2)
{
String url = makeURL(points.get(0).latitude,points.get(0).longitude,points.get(1).latitude,points.get(1).longitude,"driving");
new connectAsyncTask(url,withIndications).execute();
return true;
}
else if(points.size() > 2)
{
String url = makeURL(points,"driving",optimize);
new connectAsyncTask(url,withIndications).execute();
return true;
}
return false;
}
private String makeURL (ArrayList<LatLng> points, String mode, boolean optimize){
StringBuilder urlString = new StringBuilder();
if(mode == null)
mode = "driving";
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append( points.get(0).latitude);
urlString.append(',');
urlString.append(points.get(0).longitude);
urlString.append("&destination=");
urlString.append(points.get(points.size()-1).latitude);
urlString.append(',');
urlString.append(points.get(points.size()-1).longitude);
urlString.append("&waypoints=");
if(optimize)
urlString.append("optimize:true|");
urlString.append( points.get(1).latitude);
urlString.append(',');
urlString.append(points.get(1).longitude);
for(int i=2;i<points.size()-1;i++)
{
urlString.append('|');
urlString.append( points.get(i).latitude);
urlString.append(',');
urlString.append(points.get(i).longitude);
}
urlString.append("&sensor=true&mode="+mode);
return urlString.toString();
}
private String makeURL (double sourcelat, double sourcelog, double destlat, double destlog,String mode){
StringBuilder urlString = new StringBuilder();
if(mode == null)
mode = "driving";
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString
.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString
.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString( destlog));
urlString.append("&sensor=false&mode="+mode+"&alternatives=true&language="+lang);
return urlString.toString();
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng( (((double) lat / 1E5)),
(((double) lng / 1E5) ));
poly.add(p);
}
return poly;
}
private class connectAsyncTask extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
String url;
boolean steps;
connectAsyncTask(String urlPass, boolean withSteps){
url = urlPass;
steps = withSteps;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if(result!=null){
driverdata.extrastmt = result;
drawPath(result, steps);
//makeT(result);
}else{
driverdata.extrastmt="null";
}
}
}
private void drawPath(String result, boolean withSteps) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(4)
.color(Color.BLUE).geodesic(true));
}
if(withSteps)
{
JSONArray arrayLegs = routes.getJSONArray("legs");
JSONObject legs = arrayLegs.getJSONObject(0);
JSONArray stepsArray = legs.getJSONArray("steps");
//put initial point
for(int i=0;i<stepsArray.length();i++)
{
Step step = new Step(stepsArray.getJSONObject(i));
mMap.addMarker(new MarkerOptions()
.position(step.location)
.title(step.distance)
.snippet(step.instructions)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
}
}
catch (JSONException e) {
}
}
/**
* Class that represent every step of the directions. It store distance, location and instructions
*/
private class Step
{
public String distance;
public LatLng location;
public String instructions;
Step(JSONObject stepJSON)
{
JSONObject startLocation;
try {
distance = stepJSON.getJSONObject("distance").getString("text");
startLocation = stepJSON.getJSONObject("start_location");
location = new LatLng(startLocation.getDouble("lat"),startLocation.getDouble("lng"));
try {
instructions = URLDecoder.decode(Html.fromHtml(stepJSON.getString("html_instructions")).toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
and finally JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
URL urlnew = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) urlnew.openConnection();
is = new BufferedInputStream(urlConnection.getInputStream());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.d("JSON_RUTA", json);
return json;
}
}
Please I need assistance, and moreover it fetches the data but on the map activity i.e, servicing activity the toast delivers nothing, once you press back and then again on button to start servicing activity, the toast delivers previous results, but no route can be seen on map.
I found solution, basically, I was calling route.drawroute(), before adding the points to the list, so it was returning null.
NEW VERSION 1.1
Hi guys. I tried to follow your recommendations and now i'm trying to redo the code.
I added this part of the code to work on the Main Thread the GoogleMaps markers.
The problem is, when i call the Ubic() function, i get this error:
http://i.imgur.com/QD7JZjRh.jpg
http://i.imgur.com/xvzJ9ckh.jpg
This is the code that i added an the error is caused by String Latlon[][] = com.Ubic();
public class BuscarContrincantes extends FragmentActivity implements
LocationListener {
GoogleMap googlemapa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buscarcontrincante);
SupportMapFragment maps = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googlemapa = maps.getMap();
googlemapa.setMyLocationEnabled(true);
googlemapa.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googlemapa.getUiSettings().setCompassEnabled(true);
googlemapa.getUiSettings().setZoomControlsEnabled(true);
googlemapa.getUiSettings().setAllGesturesEnabled(true);
double latitud;
double longitud;
String nombre;
Datos com = new Datos();
String latlon[][] = com.Ubic(); //HERE IS THE PROBLEM!
for (int i = 0; i < latlon.length - 1; i++) {
latitud = Double.parseDouble(latlon[i][0]);
longitud = Double.parseDouble(latlon[i][3]);
nombre = (latlon[i][2]);
LatLng posicion = new LatLng(latitud, longitud);
googlemapa.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.icono_canchas))
.position(posicion).title(nombre));
}
}
VERSION 1.0
I'm having a problem with a project that i'm doing for my college.
Actually, i'm trying to set a Marker on a Map (With Google Maps) that his information is on a MySQL Database.
The code is:
BuscarContrincantes.java
public class BuscarContrincantes extends FragmentActivity implements
LocationListener {
GoogleMap googlemapa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buscarcontrincante);
SupportMapFragment maps = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googlemapa = maps.getMap();
googlemapa.setMyLocationEnabled(true);
googlemapa.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googlemapa.getUiSettings().setCompassEnabled(true);
googlemapa.getUiSettings().setZoomControlsEnabled(true);
googlemapa.getUiSettings().setAllGesturesEnabled(true);
new RetreiveFeedTask().execute();
}
class RetreiveFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
double lat;
double lon;
String nombre;
Datos com = new Datos(); // File Datos.java
String latlon[][] = com.Ubic();
for (int i = 0; i < latlon.length - 1; i++) {
lat = Double.parseDouble(latlon[i][0]);
lon = Double.parseDouble(latlon[i][4]);
nombre = (latlon[i][2]);
LatLng pos3 = new LatLng(lat, lon);
googlemapa.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.icono_canchas))
.position(pos3).title(nombre));
}
return null;
}
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}}
Datos.java
public class Datos {
public String[][] Ubic() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://MY.IP/FOLDER/QUERY.php");
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
JSONArray arr = object.getJSONArray("products");
String[] lat = new String[arr.length()+1];
String[] lon = new String[arr.length()+1];
String[] nombre = new String[arr.length() + 1];
String[][] latlon = new String[arr.length() + 1][5];
for (int i = 0; i < arr.length(); i++) {
lat[i] = arr.getJSONObject(i).getString("latitude");
lon[i] = arr.getJSONObject(i).getString("longitude");
name[i] = arr.getJSONObject(i).getString("name");
latlon[i][0] = lat[i];
latlon[i][6] = lon[i];
latlon[i][2] = name[i];
}
return latlon;
} catch (JSONException e) {
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
private static String parse(String string) {
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
}
return answer;
}}
This code is trying to get Latitude, Longitude and Name of an object that is on a MySQL Database and must put this object on the Map, but i'm getting the AsynkTask #1 Error and i don't know why this is happening.
¿Can you help me, please? I'm getting really mad with this code and i don't know why this isn't working.
P.S: Sorry for my bad English. I'm from Chile :P
You can not access the GoogleMap instance at doInBackground method. The GoogleMap can only be read and modified from the main thread. Just the HTTP request shall be on background task.
You need to modify doInBackground to return the list of coordinates and implement the GoogleMap update at onPostExecute method (at main thread).
Here is the code based on Version 1.1:
GoogleMap googlemapa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buscarcontrincante);
SupportMapFragment maps = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googlemapa = maps.getMap();
googlemapa.setMyLocationEnabled(true);
googlemapa.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googlemapa.getUiSettings().setCompassEnabled(true);
googlemapa.getUiSettings().setZoomControlsEnabled(true);
googlemapa.getUiSettings().setAllGesturesEnabled(true);
new RetreiveFeedTask().execute();
}
class RetreiveFeedTask extends AsyncTask<Void, Void, String[][]> {
#Override
protected String[][] doInBackground(Void... args) {
// Execute the HTTP request on background task
Datos com = new Datos(); // File Datos.java
return com.Ubic();
}
#Override
protected void onPostExecute(String[][] latlon) {
double latitud;
double longitud;
String nombre;
// Update the UI
for (int i = 0; i < latlon.length - 1; i++) {
latitud = Double.parseDouble(latlon[i][0]);
longitud = Double.parseDouble(latlon[i][3]);
nombre = (latlon[i][2]);
LatLng posicion = new LatLng(latitud, longitud);
googlemapa.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.icono_canchas)).position(posicion).title(nombre));
}
}
}