MyLocation.Java
package com.example.mycoordinate;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.Polyline;
import com.google.maps.android.SphericalUtil;
public class MyLocation extends AppCompatActivity implements LocationListener {
private GoogleMap googleMap;
private SupportMapFragment supportMapFragment;
private MarkerOptions place1, place2;
//getLocation()
LocationManager locationManager;
String locationText = "";
String locationLatitude = "";
String locationLongitude = "";
private Handler mHandler ;
private int mInterval = 3000; // after the coordinate is found, refresh every 3 seconds.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_offline);
supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
//Alert Dialog
AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
MyLocation.this);
// Setting Dialog Title
alertDialog2.setTitle("Notification");
// Setting Dialog Message
String string1 = "Give it 10-15 seconds for your coordinates to update. Keep moving around and you will see coordinates update.";
alertDialog2.setMessage(string1);
// Setting Icon to Dialog
alertDialog2.setIcon(R.drawable.ic_launcher_background);
// Setting Positive "Yes" Btn
// alertDialog2.setPositiveButton("Continue",
// new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
//
// }
// });
// Showing Alert Dialog
alertDialog2.show();
Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
public void run() {
mHandler = new Handler();
startRepeatingTask();
}
}, 1000); //5 seconds
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
}
#Override
public void onDestroy() {
super.onDestroy();
stopRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
final EditText yourlat = (EditText) findViewById(R.id.yourLat);
final EditText yourlong = (EditText) findViewById(R.id.yourLong);
try {
getLocation(); //this function can change value of mInterval.
if (locationText.toString() == "") {
Toast.makeText(getApplicationContext(), "Locating us...", Toast.LENGTH_LONG).show();
} else {
yourlat.setText(locationLatitude.toString());
yourlong.setText(locationLongitude.toString());
}
} finally {
mHandler.postDelayed(mStatusChecker, mInterval);
}
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 5, (LocationListener) this);
}
catch(SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
locationText = location.getLatitude() + "," + location.getLongitude();
locationLatitude = location.getLatitude() + "";
locationLongitude = location.getLongitude() + "";
final LatLng home = new LatLng(1.363451, 103.834337); //HOME
final LatLng current = new LatLng(location.getLatitude(), location.getLongitude()); //current position
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
// double zoomLevel = googleMap.getCameraPosition().zoom;
// if (zoomLevel < 8) {
// zoomLevel = 18.0;
// }
// googleMap.clear();
//googleMap.addMarker(new MarkerOptions().position(current_position).title("Current Location"));
//googleMap.moveCamera(CameraUpdateFactory.newLatLng(current_position) );
//googleMap.animateCamera( CameraUpdateFactory.zoomTo( (float) zoomLevel) );
//googleMap.addMarker(new MarkerOptions().position(home).title("Home"));
//googleMap.moveCamera(CameraUpdateFactory.newLatLng(place1.getPosition()) );
place1 = new MarkerOptions().position(current).title("Current");
place2 = new MarkerOptions().position(home).title("Home");
googleMap.addMarker(place1);
googleMap.addMarker(place2);
//Route between two points
new FetchURL(MyLocation.this).execute(getUrl(place1.getPosition(), place2.getPosition(), "driving"), "driving" );
//distance between two points in a Straight Line
Double distance = SphericalUtil.computeDistanceBetween(place1.getPosition(), place2.getPosition());
CameraPosition googlePlex = CameraPosition.builder()
.target(place1.getPosition())
.zoom(16)
.bearing(0)
//.tilt(45)
.build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 10000, null);
Log.d("Location", "Distance: " + distance );
}
});
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MyLocation.this, "Please Enable GPS", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
private String getUrl(LatLng origin, LatLng dest, String directionMode) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Mode
String mode = "mode=" + directionMode;
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + mode;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters + "&key=" + getString(R.string.google_maps_key);
Log.d("TEST", "getUrl: " + url);
return url;
}
}
FetchURL.java
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class FetchURL extends AsyncTask<String, Void, String> {
Context mContext;
String directionMode = "driving";
public FetchURL(Context mContext) {
this.mContext = mContext;
}
#Override
protected String doInBackground(String... strings) {
// For storing data from web service
String data = "";
directionMode = strings[1];
try {
// Fetching the data from web service
data = downloadUrl(strings[0]);
Log.d("mylog", "Background task data " + data.toString());
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
PointsParser parserTask = new PointsParser(mContext, directionMode);
// Invokes the thread for parsing the JSON data
parserTask.execute(s);
}
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();
Log.d("mylog", "Downloaded URL: " + data.toString());
br.close();
} catch (Exception e) {
Log.d("mylog", "Exception downloading URL: " + e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
}
PointsParser.java
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class PointsParser extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
TaskLoadedCallback taskCallback;
String directionMode = "driving";
public PointsParser(Context mContext, String directionMode) {
this.taskCallback = (TaskLoadedCallback) mContext; <---- this is the error
this.directionMode = directionMode;
}
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
Log.d("mylog", jsonData[0].toString());
DataParser parser = new DataParser();
Log.d("mylog", parser.toString());
// Starts parsing data
routes = parser.parse(jObject);
Log.d("mylog", "Executing routes");
Log.d("mylog", routes.toString());
} catch (Exception e) {
Log.d("mylog", e.toString());
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
if (directionMode.equalsIgnoreCase("walking")) {
lineOptions.width(10);
lineOptions.color(Color.MAGENTA);
} else {
lineOptions.width(20);
lineOptions.color(Color.RED);
}
Log.d("mylog", "onPostExecute lineoptions decoded");
}
// Drawing polyline in the Google Map for the i-th route
if (lineOptions != null) {
//mMap.addPolyline(lineOptions);
taskCallback.onTaskDone(lineOptions);
} else {
Log.d("mylog", "without Polylines drawn");
}
taskCallback.onTaskDone();
}
}
TaskLoadedCallback.java
public interface TaskLoadedCallback {
void onTaskDone(Object... values);
}
It has been almost a week trying to understand and trying to fix this the error Below.
2019-08-12 14:29:01.822 14672-14672/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2019-08-12 14:29:01.824 14672-14672/? E/Zygote: accessInfo : 1
2019-08-12 14:29:01.866 14672-14680/? E/le.mycoordinat: Unable to peek into adb socket due to error. Closing socket.: Connection reset by peer
2019-08-12 14:29:03.831 14672-14672/com.example.mycoordinate E/ViewRootImpl#c1f726b[MyLocation]: mStopped=false mHasWindowFocus=true mPausedForTransition=false
2019-08-12 14:29:03.859 14672-14672/com.example.mycoordinate E/ViewRootImpl: sendUserActionEvent() returned.
2019-08-12 14:29:07.662 14672-14672/com.example.mycoordinate E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mycoordinate, PID: 14672
java.lang.ClassCastException: com.example.mycoordinate.MyLocation cannot be cast to com.example.mycoordinate.TaskLoadedCallback
at com.example.mycoordinate.PointsParser.<init>(PointsParser.java:20)
at com.example.mycoordinate.FetchURL.onPostExecute(FetchURL.java:44)
at com.example.mycoordinate.FetchURL.onPostExecute(FetchURL.java:18)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.access$600(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:6986)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
Any kindhearted individual who can help me with this? It has been almost a week since i started this journey. I already passed (MyLocation.this - as reference to the activity) but it still doesnt work... do note my Google API is working fine.
Please help.
This is because you are passing MyLocation to PointsParser and try to cast it to TaskLoadedCallback in this.taskCallback = (TaskLoadedCallback) mContext;, add TaskLoadedCallback to implements in MyLocation
public class MyLocation extends AppCompatActivity implements LocationListener, TaskLoadedCallback {
}
Related
I have tried many changes researching on google but my problem isn't resolved. I have an URL which contains following data. On map it should show more than one marker as I have 9 coordinates. But it is showing one marker with coordinates of last values of response. Any help can be appreciated.
{
"status":200,
"response":[
{
"docId":"1",
"docName":"Madan",
"docMobileNumber":"9676499774",
"location":"S R Nagar",
"specialization":"ENT",
"avaliablity":"Available",
"lat":"17.4436",
"log":"78.4458"
},
{
"docId":"2",
"docName":"Kumar",
"docMobileNumber":"9052598855",
"location":"KPHB",
"specialization":"Pediatrician",
"avaliablity":"Available",
"lat":"17.4948",
"log":"78.3996"
},
{
"docId":"3",
"docName":"charan",
"docMobileNumber":"8080809089",
"location":"Ameerpet",
"specialization":"Dentist",
"avaliablity":"Available",
"lat":"17.4375",
"log":"78.4483"
},
{
"docId":"4",
"docName":"Vamsy",
"docMobileNumber":"7777778888",
"location":"Kukatpally",
"specialization":"Orthopedic",
"avaliablity":"Available",
"lat":"17.4948",
"log":"78.3996"
},
{
"docId":"5",
"docName":"Ganesh",
"docMobileNumber":"9878686544",
"location":"Dilsuk Nagar",
"specialization":"Dermatologist",
"avaliablity":"Available",
"lat":"17.3688",
"log":"78.5247"
},
{
"docId":"6",
"docName":"Savitri",
"docMobileNumber":"8786599452",
"location":" West Marredpally",
"specialization":"Physician",
"avaliablity":"Not Available",
"lat":"17.4500",
"log":"78.5006"
},
{
"docId":"7",
"docName":"Sandhya",
"docMobileNumber":"9873243687",
"location":"Bowenpally",
"specialization":"Eye Specialist",
"avaliablity":"Available",
"lat":"17.898",
"log":"78.5008"
},
{
"docId":"8",
"docName":"Padma",
"docMobileNumber":"9768832418",
"location":"Kompally",
"specialization":"Cardiologist",
"avaliablity":"Not Available",
"lat":"17.5600",
"log":"78.5343"
},
{
"docId":"9",
"docName":"Priya",
"docMobileNumber":"9898767654",
"location":"Tirumalgiri",
"specialization":"Nerphrologist",
"avaliablity":"Available",
"lat":"17.787",
"log":"78.9805"
}
]
}
package com.example.charan.markermap;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
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.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
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.util.ArrayList;
import java.util.HashMap;
public class Maps3 extends FragmentActivity {
private GoogleMap mMap;
ArrayList<HashMap<String, Double>> locationList = new ArrayList<HashMap<String, Double>>();
JSONArray locations = new JSONArray();
int json1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
new TaskRead().execute();
}
public class TaskRead extends AsyncTask<Void, Void, Void> implements OnMapReadyCallback {
ProgressDialog pg;
Double latitude, longitude;
protected void onPreExecute() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
pg = ProgressDialog.show(Maps3.this, "Please Wait", "Conecting to Server");
pg.setCancelable(true);
}
protected Void doInBackground(Void... params) {
try {
String url = "http://192.168.1.33:8282/DocFinderServices/doctorService/doctorsList";
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream inputStreamResponse = entity.getContent();
String str = convertStreamToString(inputStreamResponse);
if (str != null) {
try {
JSONObject jsonObj = new JSONObject(str);
// Getting JSON Array node
locations = jsonObj.getJSONArray("response");
json1 = jsonObj.getInt("status");
// looping through All records
for (int i = 0; i < locations.length(); i++) {
JSONObject c = locations.getJSONObject(i);
latitude = c.getDouble("lat");
longitude = c.getDouble("log");
// tmp hashmap for single contact
HashMap<String, Double> location = new HashMap<>();
// adding each child node to HashMap key => value
location.put("latitude", latitude);
location.put("longitude", longitude);
locationList.add(location);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void gmap) {
mMap.clear();
Marker[] allMarkers = new Marker[locationList.size()];
Toast.makeText(Maps3.this, "The list size is " + locationList.size(), Toast.LENGTH_SHORT).show();
for (int i = 0; i < locationList.size(); i++) {
if (mMap != null && json1 == 200) {
for (int j = 0; j < locationList.size(); j++) {
LatLng latLng = new LatLng(latitude, longitude);
allMarkers[i] = mMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ok)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14.0f));
mMap.getUiSettings().isZoomGesturesEnabled();
}
} else {
Toast.makeText(Maps3.this, "Oops..their is no map........", Toast.LENGTH_SHORT).show();
}
}
pg.dismiss();
}
public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
}
}
Try with execute TaskRead after you got callback onMapReady().
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Set Zoom Controls and Gestures on map
mMap.getUiSettings().setZoomControlsEnabled(true)
mMap.getUiSettings().setZoomGesturesEnabled(true)
new TaskRead().execute();
}
Implements OnMapReadyCallback inside FragmentActivity and initialize your SupportMapFragment in onCreate method like below.
public class Maps3 extends FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
Try to set zoom Controls and Gestures on map and try with zoom in or zoom out and see, is there other marker added on map or not ?
Check my updated onMapReady method.
I have just changed LatLng latLng = new LatLng(latitude, longitude); to new values of getting key pair values as
LatLng latLng = new LatLng(Double.valueOf(locationList.get(j).get("latitude")), Double.valueOf(locationList.get(j).get("longitude")));. Now it is working.
I'm try to develop a location based app. I try to draw a route but program returns to me a NullPointerException.
I faced this problem at line 361.
MapsActivity.java
package com.example.tcarcelik.glympse;
/**
* Created by TCARCELIK on 09.07.2015.
*/
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.ads.formats.NativeContentAd;
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.SupportMapFragment;
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.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
public class MapsActivity extends FragmentActivity implements Parcelable,LocationListener {
LatLng destination;
Polyline line;
Button mBtnDest;
Button btnDraw;
Button btnOk;
Button btnNextStep;
int counter;
GoogleMap mMap;
EditText editPlace_Dest;
ArrayList<LatLng> markerPoints;
ArrayList<LatLng> list;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
double mLatitude = 0;
double mLongitude = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
markerPoints = new ArrayList<LatLng>();
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
Criteria criteria = new Criteria();
btnDraw = (Button) findViewById(R.id.btn_draw);
btnOk = (Button) findViewById(R.id.btn_ok);
mMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
destination = point;
mMap.clear();
drawMarker(point);
markerPoints.add(point);
FrameLayout mapLayout = (FrameLayout)findViewById(R.id.map);
btnDraw.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
double lat1 = mMap.getMyLocation().getLatitude();
double long1 = mMap.getMyLocation().getLongitude();
LatLng latlng = new LatLng(lat1, long1);
String url = getDirectionsUrl(latlng, destination);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
});
// Button of OK
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("listToPass", list);
// CameraPosition myCam = mMap.getCameraPosition();
ArrayList<Double> first_param = new ArrayList<Double>();
ArrayList<Double> second_param = new ArrayList<Double>();
for(LatLng point:list){
first_param.add(point.latitude);
second_param.add(point.longitude);
}
Collections.sort(first_param);
Collections.sort(second_param);
double lat_min = first_param.get(0);
double lat_max = first_param.get(first_param.size()-1);
double lng_min = second_param.get(0);
double lng_max = second_param.get(second_param.size()-1);
LatLng bound_1 = new LatLng(lat_min,lng_min);
LatLng bound_2 = new LatLng(lat_max,lng_max);
LatLngBounds mainbound = new LatLngBounds(bound_1,bound_2);
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mainbound,100));
CameraPosition myCam = mMap.getCameraPosition();
i.putExtra("cameraPosition", myCam);
startActivity(i);
}
});
}
});
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, (LocationListener) this);
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setMyLocationEnabled(true);
if (mMap != null) {
// setUpMap();
}
}
}
public GoogleMap get_MapsMap(){
return mMap;
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+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();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
/** A class, to download Places from Geocoding webservice */
private class DownloadTask extends AsyncTask<String, Integer, String> {
String data = null;
ProgressDialog progressDialog;
// Invoked by execute() method of this object
#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
// Draw path'in onPostExecute ' u
#Override
protected void onPostExecute(String result){
// Instantiating ParserTask which parses the json data from Geocoding webservice
// in a non-ui thread
ParserTask parserTask = new ParserTask();
// Start parsing the places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
drawPath(result); // Ben ekledim
if(progressDialog.isShowing()){
progressDialog.dismiss();
}
}
#Override
protected void onPreExecute() {
if(progressDialog == null){
progressDialog = new ProgressDialog(MapsActivity.this);
progressDialog.setMessage("Drawing route");
progressDialog.show();
}
}
}
/** A class to parse the Geocoding Places in non-ui thread */
class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
GeocodeJSONParser parser = new GeocodeJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a an ArrayList */
places = parser.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,String>> list){
}
}
//YENI EKLENENLER
private void drawMarker(LatLng point){
markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
mMap.addMarker(options);
}
public void drawPath(String result){
try {
final JSONObject jsonObject = new JSONObject(result);
JSONArray routeArray = jsonObject.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
list = (ArrayList<LatLng>) decodePoly(encodedString);
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = mMap.addPolyline(options);
// Animate camera after drawing route
ArrayList<Double> first_param = new ArrayList<Double>();
ArrayList<Double> second_param = new ArrayList<Double>();
for(LatLng point:list){
first_param.add(point.latitude);
second_param.add(point.longitude);
}
Collections.sort(first_param);
Collections.sort(second_param);
double lat_min = first_param.get(0);
double lat_max = first_param.get(first_param.size()-1);
double lng_min = second_param.get(0);
double lng_max = second_param.get(second_param.size()-1);
LatLng bound_1 = new LatLng(lat_min,lng_min);
LatLng bound_2 = new LatLng(lat_max,lng_max);
LatLngBounds mainbound = new LatLngBounds(bound_1,bound_2);
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(mainbound, 100));
// Animate camera after drawing route
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
mMap.moveCamera(cameraUpdate);
locationManager.removeUpdates((LocationListener) this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
//YENI EKLENENLER
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;
}
public void onMyLocationChange(Location location) {
// TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
// tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
please, debug and make sure you are correctly downloading the file, check the downloadUrl(String strUrl) method and make sure it reaches line 256. i believe the problem is with the download method.
how to start activity when click on marker with json and clustering
my map is already clustering but i cant start to new activity when click on marker without title
this is my code
package tmg.tower;
/**
* Created by DIMAS on 25/06/2015.
*/
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
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.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.maps.android.clustering.ClusterManager;
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.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends Activity implements GoogleMap.OnMarkerClickListener, View.OnClickListener {
private JSONParser json;
private LatLng myLocation;
ArrayList<HashMap<String, String>> dataMap = new ArrayList<HashMap<String, String>>();
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
Server serv = new Server();
String conn = serv.connection();
String url = conn + "********";
JSONArray str_json = null;
static final int showerror = 1;
public static final String SP = "shareAt";
SharedPreferences shareAt;
public static final String KEY_LAT_TUJUAN = "lat_tujuan";
public static final String KEY_LNG_TUJUAN = "lng_tujuan";
static final LatLng AWAL = new LatLng(3.584695, 98.675079);
Button mBtnFind;
EditText etPlace;
Button searchlist;
private ClusterManager<MyItem> mClusterManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LatLng myPosition;
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("GPS Disabled, Buka Setting dan Aktifkan GPS?")
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
finish();
}
})
.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
finish();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
Toast.makeText(getApplicationContext(), "GPS Enabled", Toast.LENGTH_LONG).show();
}
if (cek_status(this)) {
Server serv = new Server();
conn = serv.connection();
new getListInfo().execute();
} else {
showDialog(showerror);
}
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment) myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
myMap.getUiSettings().setZoomControlsEnabled(true);
myMap.getUiSettings().setCompassEnabled(true);
myMap.getUiSettings().setMyLocationButtonEnabled(true);
myMap.getUiSettings().setAllGesturesEnabled(true);
myMap.setTrafficEnabled(true);
myMap.setOnMarkerClickListener(this);
myMap.moveCamera(CameraUpdateFactory.newLatLngZoom(AWAL, 15));
myMap.setBuildingsEnabled(true);
myMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
mBtnFind = (Button) findViewById(R.id.btn_show);
etPlace = (EditText) findViewById(R.id.et_place);
searchlist = (Button) findViewById(R.id.searchlist);
searchlist.setOnClickListener(this);
mBtnFind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Getting the place entered
String location = etPlace.getText().toString();
if(location==null || location.equals("")){
Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show();
return;
}
String url = "https://**********";
try {
// encoding special characters like space in the user input place
location = URLEncoder.encode(location, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String siteid = "Site_ID=" + location;
String sensor = "sensor=false";
// url , from where the geocoding data is fetched
url = url + siteid + "&" + sensor;
// Instantiating DownloadTask to get places from Google Geocoding service
// in a non-ui thread
DownloadTask downloadTask = new DownloadTask();
// Start downloading the geocoding places
downloadTask.execute(url);
}
});
}
public void onClick (View v){
Intent i = new Intent(MainActivity.this,Search.class);
startActivity(i);
}
public boolean cek_status(Context cek) {
ConnectivityManager cm = (ConnectivityManager) cek.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case showerror:
AlertDialog.Builder errorDialog = new AlertDialog.Builder(this);
errorDialog.setTitle("Error Connection");
errorDialog.setMessage("Please check your internet connection");
errorDialog.setNeutralButton("exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
Intent exit = new Intent(Intent.ACTION_MAIN);
exit.addCategory(Intent.CATEGORY_HOME);
exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.this.finish();
startActivity(exit);
}
});
AlertDialog errorAlert = errorDialog.create();
return errorAlert;
default:
break;
}
return dialog;
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
#SuppressLint("LongLogTag")
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;
}
/** A class, to download Places from Geocoding webservice */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#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){
// Instantiating ParserTask which parses the json data from Geocoding webservice
// in a non-ui thread
ParserTask parserTask = new ParserTask();
// Start parsing the places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
class getListInfo extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Loading server...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
JSONObject json = jParser.AmbilJson(url);
try {
str_json = json.getJSONArray("tower");
for (int i = 0; i < str_json.length(); i++) {
JSONObject ar = str_json.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("Site ID", ar.getString("Site ID"));
map.put("Site Name", ar.getString("Site Name"));
map.put("Address", ar.getString("Address"));
map.put("Lattitude", ar.getString("Lattitude"));
map.put("Longitude", ar.getString("Longitude"));
dataMap.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
mClusterManager = new ClusterManager<MyItem>(getApplicationContext(), myMap);
myMap.setOnCameraChangeListener(mClusterManager);
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
for (int i = 0; i < dataMap.size(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
List<MyItem> items = new ArrayList<MyItem>();
map = dataMap.get(i);
mClusterManager.addItem(new MyItem(Double.parseDouble(map.get("Lattitude")), Double.parseDouble(map.get("Longitude"))));
}
}
});
}
}
class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
GeocodeJSONParser parser = new GeocodeJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a an ArrayList */
places = parser.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,String>> list){
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("Lattitude"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("Longitude"));
// Getting name
String name = hmPlace.get("Site ID");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Locate the first location
if(i==0)
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
TextView tvLocInfo;
#Override
public boolean onMarkerClick(Marker marker) {
myLocation = new LatLng(myMap.getMyLocation().getLatitude(), myMap.getMyLocation().getLongitude());
if (myLocation != null) {
Bundle bundle = new Bundle();
bundle.putDouble(KEY_LAT_TUJUAN, marker.getPosition().latitude);
bundle.putDouble(KEY_LNG_TUJUAN, marker.getPosition().longitude);
shareAt = getBaseContext().getSharedPreferences(SP, 0);
SharedPreferences.Editor editor = shareAt.edit();
String replace_string_first = marker.getTitle().replace(" ", "_");
editor.putString("Site ID", replace_string_first);
editor.putString("Lattitude", replace_string_first);
editor.putString("Longitude", replace_string_first);
editor.commit();
Intent intent = new Intent(MainActivity.this, Main.class);
intent.putExtras(bundle);
intent.putExtra("Site ID", replace_string_first);
intent.putExtra("Lattitude", replace_string_first);
intent.putExtra("Longitude", replace_string_first);
startActivity(intent);
}
return false;
}
}
how to get intent json object without marker.getTitle ?
thanks for help
I'm creating an App that will show the location of the user and put a marker to that position. After the user moves. The marker would be removed and a new marker would be created. Now. I want to make markers on Point A and Point B to be hardcoded into the app and show the route on the map. It shall use the nearest road on the map. I've done some research but only find old code which dated 5 years back. Could anyone be kind enough to guide me through this.
The Point A and Point B is on LocationChanged method.
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
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 android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements LocationListener {
private GoogleMap map;
private LocationManager locationManager;
private String provider;
LatLng coordinate;
Marker startPerc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabledGPS) {
Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
Toast.makeText(this, "Selected Provider " + provider,
Toast.LENGTH_SHORT).show();
onLocationChanged(location);
} else {
//do something
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 300, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(this, "Location " + lat+","+lng,
Toast.LENGTH_LONG).show();
LatLng coordinate = new LatLng(lat, lng);
Toast.makeText(this, "Location " + coordinate.latitude+","+coordinate.longitude,
Toast.LENGTH_LONG).show();
if(map!=null){
map.clear();
}
//map.clear();
GoogleMap map;
if(startPerc!=null){
startPerc.remove();
}
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
startPerc = map.addMarker(new MarkerOptions()
.position(coordinate)
.title("Start")
.snippet("Your Position")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 20));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.position(new LatLng(3.214732, 101.747047))
.title("Point A")
.snippet("Bus Stop")
.flat(true));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.position(new LatLng(3.214507, 101.749697))
.title("Point B")
.snippet("Bus Stop")
.flat(true));
startPerc.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
}
# Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
void Delay(int Seconds){
long Time = 0;
Time = System.currentTimeMillis();
while(System.currentTimeMillis() < Time+(Seconds*1000));
}
}
New code provided by K Neeraj. It still crash sadly please check.
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
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.google.android.gms.maps.model.PolylineOptions;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements LocationListener {
private GoogleMap map;
private LocationManager locationManager;
private String provider;
LatLng coordinate;
Marker startPerc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabledGPS) {
Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
Toast.makeText(this, "Selected Provider " + provider,
Toast.LENGTH_SHORT).show();
onLocationChanged(location);
} else {
//do something
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 300, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(this, "Location " + lat+","+lng,
Toast.LENGTH_LONG).show();
LatLng coordinate = new LatLng(lat, lng);
Toast.makeText(this, "Location " + coordinate.latitude+","+coordinate.longitude,
Toast.LENGTH_LONG).show();
if(map!=null){
map.clear();
}
GoogleMap map;
if(startPerc!=null){
startPerc.remove();
}
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
startPerc = map.addMarker(new MarkerOptions()
.position(coordinate)
.title("Start")
.snippet("Your Position")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 12));
startPerc.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
// Assign your origin and destination
// These points are your markers coordinates
LatLng origin = new LatLng(3.214732, 101.747047);
LatLng dest = new LatLng(3.214507, 101.749697);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/** 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;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#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;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
# Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
void Delay(int Seconds){
long Time = 0;
Time = System.currentTimeMillis();
while(System.currentTimeMillis() < Time+(Seconds*1000));
}
}
Then I created a new DirectionJSONParser.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.maps.model.LatLng;
public class DirectionsJSONParser {
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
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;
}
}
#Override
public void onLocationChanged(Location location) {
....
startPerc.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
// Assign your origin and destination
// These points are your markers coordinates
LatLng origin = new LatLng(3.214732, 101.747047);
LatLng dest = new LatLng(3.214507, 101.749697);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/** 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;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#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;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
Have a look at this tutorial,
Drawing Driving Route Directions Between Two Locations Using Google Directions In Google Map Android Api v2
It shows how to draw Route map between two points.
Here is the full code with minor tweaks. It's just a prettier.
import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
import com.eddress.R;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
public class GoogleMapsPath {
public GoogleMap map;
public GoogleMapsPath(Activity context, GoogleMap map, LatLng origin, LatLng dest){
this.map = map;
String url = getDirectionsUrl(origin,dest);
FetchUrl FetchUrl = new FetchUrl();
FetchUrl.execute(url);
}
// Fetches data from url passed
private class FetchUrl extends AsyncTask<String, Void, String> {
#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]);
Log.d("Background Task data", data.toString());
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
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();
Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
Log.d("ParserTask",jsonData[0].toString());
DirectionsJSONParser parser = new DirectionsJSONParser();
Log.d("ParserTask", parser.toString());
// Starts parsing data
routes = parser.parse(jObject);
Log.d("ParserTask","Executing routes");
Log.d("ParserTask",routes.toString());
} catch (Exception e) {
Log.d("ParserTask",e.toString());
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(8);
lineOptions.color(R.color.globalRedLight);
Log.d("onPostExecute","onPostExecute lineoptions decoded");
}
// Drawing polyline in the Google Map for the i-th route
if(lineOptions != null) {
map.addPolyline(lineOptions);
}
else {
Log.d("onPostExecute","without Polylines drawn");
}
}
}
}
I know this seems like a duplicate, but it's not.
I'm following a tutorial on google maps and I just cannot get throught this fail (notice this is my very first time developing in Android).
In function onCreateOptionsMenu I get the error I describe in title.
Here's my MainActivity.java (onCreateOptionsMenu is on bottom):
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class MainActivity extends FragmentActivity
{
GoogleMap map;
ArrayList<LatLng> markerPoints;
TextView tvDistanceDuration;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
TextView distancia_tiempo = new TextView(this);
this.tvDistanceDuration = distancia_tiempo; //this.findViewById(R.id.tv_distance_time);
// Initializing
this.markerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment) this.getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
this.map = fm.getMap();
// Enable MyLocation Button in the Map
this.map.setMyLocationEnabled(true);
// Setting onclick event listener for the map
this.map.setOnMapClickListener(new OnMapClickListener()
{
#Override
public void onMapClick(LatLng point)
{
// Already two locations
if (MainActivity.this.markerPoints.size() > 1)
{
MainActivity.this.markerPoints.clear();
MainActivity.this.map.clear();
}
// Adding new item to the ArrayList
MainActivity.this.markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if (MainActivity.this.markerPoints.size() == 1)
{
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (MainActivity.this.markerPoints.size() == 2)
{
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
MainActivity.this.map.addMarker(options);
// Checks, whether start and end locations are captured
if (MainActivity.this.markerPoints.size() >= 2)
{
LatLng origin = MainActivity.this.markerPoints.get(0);
LatLng dest = MainActivity.this.markerPoints.get(1);
// Getting URL to the Google Directions API
String url = MainActivity.this.getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
});
}
private String getDirectionsUrl(LatLng origin, LatLng dest)
{
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
/** 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;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>
{
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url)
{
// For storing data from web service
String data = "";
try
{
// Fetching the data from web service
data = MainActivity.this.downloadUrl(url[0]);
} catch (Exception e)
{
Log.d("Background Task", e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>>
{
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData)
{
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try
{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e)
{
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result)
{
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
if (result.size() < 1)
{
Toast.makeText(MainActivity.this.getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
return;
}
// Traversing through all the routes
for (int i = 0; i < result.size(); i++)
{
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++)
{
HashMap<String, String> point = path.get(j);
if (j == 0)
{ // Get distance from the list
distance = point.get("distance");
continue;
} else if (j == 1)
{ // Get duration from the list
duration = point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
MainActivity.this.tvDistanceDuration.setText("Distance:" + distance + ", Duration:" + duration);
// Drawing polyline in the Google Map for the i-th route
MainActivity.this.map.addPolyline(lineOptions);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
this.getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And here's activity_main.xml:
<MapFragment xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
</MapFragment>
Any ideas??