Selasa, 17 Januari 2017

Membuat Direction MultiPoint

package hu.pe.teguh.dkpp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import hu.pe.teguh.dkpp.R;

public class MyDirection extends AppCompatActivity implements OnMapReadyCallback {
String[]arNama;
String[]arAlamat;
String[]arLati;
String[]arLongi;
int jhope=0;
String multipoint="";
private GoogleMap map;
ProgressDialog pDialog;
    List<LatLng> polyz;
    JSONArray array;
//http://maps.googleapis.com/maps/api/directions/json?origin=-6.354891,106.840940&destination=-6.330698,106.834229&sensor=false&mode=driving
String mylatitude="-6.346610";//18.4543467001058,-69.9294914999045
String mylongitude="106.730735";
String mylocation="-";
String nama="";
    double slat,slon;
   
    String mylatitude2="-6.3249106";
String mylongitude2="106.66045";
String mylocation2="-";
String nama2="-";

    double dlat,dlon;


class GetDirection extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MyDirection.this);
pDialog.setMessage("Loading route. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}

protected String doInBackground(String... args) {
//https://www.google.co.id/maps/dir/-6.354891,+106.840940/-6.330698,+106.834229/@-6.3437727,106.8268826,15z/data=!3m1!4b1!4m10!4m9!1m3!2m2!1d106.84094!2d-6.354891!1m3!2m2!1d106.834229!2d-6.330698!3e0
//String stringUrl = "http://maps.googleapis.com/maps/api/directions/json?origin="+mylatitude+","+mylongitude+"&destination="+mylatitude+","+mylongitude+"&sensor=false&mode=driving";
//String stringUrl="http://maps.googleapis.com/maps/api/directions/json?origin=18.4543467001058,-69.9294914999045&destination=18.4804850999499,-69.932457299903&sensor=false&waypoints=18.4543467001058,-69.9294914999045|18.4543467001058,-69.9294914999045|18.4779706000118,-69.9026079000905|18.4794135999982,-69.8832237999886|";
//https://www.google.com/maps/dir"+mylatitude+",+"+mylongitude+"/"+mylatitude2+",+"+mylongitude2+"/@-6.3416659,106.8247612,15z/data=!4m9!4m8!1m3!2m2!1d106.831815!2d-6.351856!1m3!2m2!1d106.834229!2d-6.330698";

String stringUrl="http://maps.googleapis.com/maps/api/directions/json?origin="+slat+","+slon+"&destination="+dlat+","+dlon+"&sensor=false&waypoints="+multipoint;
Log.v("Multipoint",multipoint);
Log.v("stringUrl",stringUrl);
StringBuilder response = new StringBuilder();
try {
URL url = new URL(stringUrl);
HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()),8192);
String strLine = null;
while ((strLine = input.readLine()) != null) {
response.append(strLine);
}
input.close();
}

String jsonOutput = response.toString();
JSONObject jsonObject = new JSONObject(jsonOutput);
JSONArray routesArray = jsonObject.getJSONArray("routes");
JSONObject route = routesArray.getJSONObject(0);

JSONObject poly = route.getJSONObject("overview_polyline");
String polyline = poly.getString("points");
polyz = decodePoly(polyline);
} catch (Exception e) {}
return null;
}
protected void onPostExecute(String file_url) {
for (int i = 0; i < polyz.size() - 1; i++) {
LatLng src = polyz.get(i);
LatLng dest = polyz.get(i + 1);
Polyline line = map.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(9).color(Color.rgb(0,0,255)).geodesic(true));
}
pDialog.dismiss();
}
}

/* Method to decode polyline points */
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;
}
   
    @SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.mydirection);

//  gab=myLokasi2+"#"+myAlamat2+"#"+myLati2+"#"+myLongi2+"#@";
Intent call = this.getIntent();
String gab=call.getStringExtra("gab");
Log.v("GAB",gab);
String[]ar=gab.split("@");
jhope=ar.length;
if(jhope<2){Log.v("AR","AR Kurang");finish();}

arNama=new String[jhope];
arAlamat=new String[jhope];
arLati=new String[jhope];
arLongi=new String[jhope];

for(int j=0;j<jhope;j++){
String []mdata=ar[j].split("#");
if(mdata.length<3){
Log.v("MDATA","Mdata Kurang");finish();}
else {
arNama[j] = mdata[0];
arAlamat[j] = mdata[1];
arLati[j] = mdata[2];
arLongi[j] = mdata[3];
}
}
slat=Double.parseDouble(mylatitude);;
        slon=Double.parseDouble(mylongitude);
        try{
        slat=Double.parseDouble(arLati[0]);
        slon=Double.parseDouble(arLongi[0]);
mylocation=arAlamat[0];
nama=arNama[0];
        }
        catch(Exception e){}

dlat=Double.parseDouble(mylatitude2);;
dlon=Double.parseDouble(mylongitude2);
try{
dlat=Double.parseDouble(arLati[jhope-1]);
dlon=Double.parseDouble(arLongi[jhope-1]);
mylocation2=arNama[jhope-1]+","+arAlamat[jhope-1];
nama2=arNama[jhope-1];
}
catch(Exception e){}

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);


}

@Override
public void onMapReady(GoogleMap googleMap) {
multipoint="";
map = googleMap;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
//    ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                                          int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}

map.setMyLocationEnabled(true);

map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

map.getUiSettings().setZoomControlsEnabled(true);
map.getUiSettings().setCompassEnabled(true);
map.getUiSettings().setMyLocationButtonEnabled(true);

map.getUiSettings().setAllGesturesEnabled(true);

//map.setTrafficEnabled(true);
map.addMarker(new MarkerOptions().position(new LatLng(slat, slon)).title("Posisi Anda:"+nama).snippet(mylocation));
for(int j=1;j<jhope-1;j++) {
double mslat=Double.parseDouble(mylatitude);;
double mslon=Double.parseDouble(mylongitude);
String mmylocation="-";
String mnama="-";
//18.4543467001058,-69.9294914999045|18.4543467001058,-69.9294914999045|18.4779706000118,-69.9026079000905|18.4794135999982,-69.8832237999886|
try{
mslat=Double.parseDouble(arLati[j]);
mslon=Double.parseDouble(arLongi[j]);
mmylocation=arAlamat[j];
mnama=arNama[j];
multipoint+=arLati[j]+","+arLongi[j]+"|";
}
catch(Exception e){}

map.addMarker(new MarkerOptions().position(new LatLng(mslat, mslon)).title(mnama).snippet(mmylocation));
}
map.addMarker(new MarkerOptions().position(new LatLng(dlat, dlon)).title("Tujuan: "+nama2).snippet(mylocation2+"\nKoordinat:"+mylatitude2+","+mylongitude2));


map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(slat, slon),13));
map.animateCamera(CameraUpdateFactory.zoomTo(13), 2000, null);
new GetDirection().execute();

}

}
++++++++

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="hu.pe.teguh.dkpp.MyDirection">
   
    <fragment
        android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.SupportMapFragment"/>
       
</RelativeLayout>