Skip to content

Instantly share code, notes, and snippets.

@johnsonyeap
Created August 10, 2014 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnsonyeap/601260551560d9149d9a to your computer and use it in GitHub Desktop.
Save johnsonyeap/601260551560d9149d9a to your computer and use it in GitHub Desktop.
package com.runningbus;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
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.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class Map extends ActionBarActivity implements OnClickListener, OnMarkerClickListener, Runnable {
private GoogleMap mMap;
RelativeLayout rl_bus_stuff;
RelativeLayout rl_shadow_bus_stuff;
Location myLocation;
Marker myLocationMarker;
LatLng myLatLng;
Location busLocation;
Marker busLocationMarker;
LatLng busLatLng;
Handler handler = new Handler();
final int MARKER_UPDATE_INTERVAL = 10000;
double busLat;
double busLog;
boolean busClicked = false;
CameraPosition myPosition;
private TextView eta;
private TextView lat, lng;
private ConnectivityManager connMgr;
private NetworkInfo networkInfo;
private JSONObject jObject;
private double latitude, longitude;
private String dataSet;
private static final String GPS = "http://protected-brushlands-3658.herokuapp.com/locations.json";
private static final String DEBUG_TAG = "HttpExample";
private ArrayList<LatLng> markerPoints;
private TextView tvDistanceDuration;
private LatLng origin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
//getActionBar().setDisplayHomeAsUpEnabled(true);
initializeVariables();
Bundle para = getIntent().getExtras();
eta.setText("Estimated Arrival Time at " + para.getString("from"));
Button btn_reminder = (Button) findViewById(R.id.btn_reminder);
btn_reminder.setOnClickListener(this);
ImageButton imgbtn_close = (ImageButton) findViewById(R.id.imgbtn_close);
imgbtn_close.setOnClickListener(this);
initializeMap();
mMap.setMyLocationEnabled(true);
mMap.setOnMarkerClickListener(this);
busStopLocationInitialization();
initializeVariables();
mMap.setMyLocationEnabled(true);
if(networkInfo != null && networkInfo.isConnected())
this.run();
else
Toast.makeText(getApplicationContext(), "Please connect to the Internet", Toast.LENGTH_LONG).show();
}
@Override
public boolean onMarkerClick(final Marker marker) {
if (marker.equals(busLocationMarker))
{
rl_bus_stuff = (RelativeLayout) findViewById(R.id.rl_bus_stuff);
rl_shadow_bus_stuff = (RelativeLayout) findViewById(R.id.rl_shadow_bus_stuff);
Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
rl_bus_stuff.startAnimation(in);
rl_shadow_bus_stuff.startAnimation(in);
rl_bus_stuff.setVisibility(View.VISIBLE);
rl_shadow_bus_stuff.setVisibility(View.VISIBLE);
busClicked = true;
}
else {
marker.showInfoWindow();
//Toast.makeText(getApplicationContext(),marker.getTitle(), Toast.LENGTH_LONG).show();
}
return true;
}
private void initializeMap() {
if (mMap != null)
return;
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if(mMap == null)
Toast.makeText(this, "Google Maps not available", Toast.LENGTH_LONG).show();
}
private void busStopLocationInitialization() {
mMap.addMarker(new MarkerOptions().position(new LatLng(3.12176623135072, 101.65839032002629)).title("PASUM ->").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.124436530832811, 101.66032044678651)).title("KK12 <-").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.1246373483371, 101.660018000916)).title("IPS ->").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.126781401773583, 101.65977553364167)).title("KK5 ->").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.1267681185345895, 101.6598796606178)).title("KK12/KK5 <-").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.129108693753499, 101.66022477997881)).title("KK11 <-").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.1292194358978295, 101.66013076495967)).title("Pusat Sukan ->").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.1318163195475286, 101.6586759604345)).title("API <->").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.1296934513758935, 101.65050702564618)).title("KK10/KK8 <-").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.1298313121370103, 101.65019818742176)).title("KK8/KK10 ->").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.127584590096289, 101.650504437280772)).title("FSKTM ->").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.1275083360301627, 101.65013524393244)).title("FSKTM <-").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.1261793040424264, 101.65145699374262)).title("KK7/APM <-").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.1261243009286477, 101.65156179953505)).title("APM ->").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.1244761284684004, 101.65150713276704)).title("KK3/KK4/KK7 <-").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.1248736787851232, 101.65143117824447)).title("KK3/KK4/KK7 ->").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.121121435592652, 101.65353753024756)).title("Main Library").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
mMap.addMarker(new MarkerOptions().position(new LatLng(3.1181418530591627, 101.65930320287835)).title("KK2 <-").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_stop_logo)));
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_reminder:
Intent Reminder = new Intent("com.runningbus.REMINDER");
startActivity(Reminder);
break;
case R.id.imgbtn_close:
Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
rl_bus_stuff.startAnimation(out);
rl_shadow_bus_stuff.startAnimation(out);
rl_bus_stuff.setVisibility(View.INVISIBLE);
rl_shadow_bus_stuff.setVisibility(View.INVISIBLE);
busClicked = false;
break;
}
}
private void initializeVariables() {
eta = (TextView) findViewById(R.id.tvETA);
connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
networkInfo = connMgr.getActiveNetworkInfo();
}
private class getData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
try {
dataSet = downloadUrlx(urls[0]);
} catch(IOException e) {
return "Unable to retrieve web page. URL may be invalid";
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
jObject = new JSONObject(dataSet);
latitude = Double.parseDouble(jObject.getString("lat"));
longitude = Double.parseDouble(jObject.getString("lng"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
busLocationMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("E9").icon(BitmapDescriptorFactory.fromResource(R.drawable.rb_bus_logo)));
myPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(18).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(myPosition));
origin = new LatLng(latitude, longitude);
LatLng dest = new LatLng(2.926694, 101.790518);
// 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);
}
}
//Fetches and processes the web page content and passes back a result string.
private String downloadUrlx(String myurl) throws IOException {
String contentAsString;
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The GET response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException {
Reader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
@Override
public void run() {
// TODO Auto-generated method stub
new getData().execute(GPS);
handler.postDelayed(this, 2000);
}
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);
Log.d("Review the data received from Google", routes.toString());
}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 = "";
int duration_int= 0;
TextView time = (TextView) findViewById(R.id.txtv_time);
if(result.size()<1){
Toast.makeText(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 = (String)point.get("distance");
continue;
}else if(j==1){ // Get duration from the list
duration = (String)point.get("duration");
String[] separated = duration.split(" ");
duration_int = Integer.parseInt(separated[0]);
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);
}
duration_int = duration_int * 60 * 1000;
SimpleDateFormat sdfDateTime = new SimpleDateFormat("HH:mm", Locale.US);
String newtime = sdfDateTime.format(new Date(System.currentTimeMillis()+ duration_int));
time.setText(newtime);
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment