1

I am a newbie in android programming. I already retrieved LatLng from the database and the current location. The problem is i don't know how to draw path from the two marker. Thank you :) This is my Map Activity.

public class ModelMap extends AppCompatActivity  implements OnMapReadyCallback, View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

Button btnGo;
AutoCompleteTextView etSearch;

LatLng latLng;
GoogleMap mGoogleMap;
SupportMapFragment mFragment;
Marker currLocationMarker;

LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_model_map);

    btnGo = (Button) findViewById(R.id.btnGo);
    etSearch = (AutoCompleteTextView) findViewById(R.id.etSearch);
    btnGo.setOnClickListener(this);


    getMap();
}

@Override
public void onClick(View view) {

            ArrayList<HashMap<String, String>> location = null;
            String url = "http://enyatravel.com/maps/mapsdata/mapsModel.php";

            try {
                JSONArray data = new JSONArray(getHttpGet(url));
                location = new ArrayList<HashMap<String, String>>();
                HashMap<String, String> map;

                for (int i = 0; i < data.length(); i++) {
                    JSONObject c = data.getJSONObject(i);

                    map = new HashMap<String, String>();
                    map.put("location_id", c.getString("location_id"));
                    map.put("latitude", c.getString("latitude"));
                    map.put("longitude", c.getString("longitude"));
                    map.put("name", c.getString("name"));
                    location.add(map);


                }
            } catch (JSONException e) {

                e.printStackTrace();
            }
            mGoogleMap.getUiSettings().setMapToolbarEnabled(false);
            mGoogleMap.getUiSettings().setCompassEnabled(false);
            mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);

            //zoom

            Double latitude = Double.parseDouble(location.get(0).get("latitude").toString());
            Double longitude = Double.parseDouble(location.get(0).get("longitude").toString());
            LatLng coordinate = new LatLng(latitude, longitude);
            mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));

            //marker

            for (int i = 0; i < location.size(); i++) {
                latitude = Double.parseDouble(location.get(i).get("latitude").toString());
                longitude = Double.parseDouble(location.get(i).get("longitude").toString());
                String name = location.get(i).get("name").toString();
                MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title(name);
                mGoogleMap.addMarker(marker);

            }




}


public void getMap() {
    if (Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googlemaps);
    mFragment.getMapAsync(this);
}

public static String getHttpGet(String url) {
    StringBuilder str = new StringBuilder();
    HttpClient client = new DefaultHttpClient();

    HttpGet httpget = new HttpGet(url);
    try {
        HttpResponse response = client.execute(httpget);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) { // Download OK
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
        } else {
            Log.e("Log", "Failed to download result..");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return str.toString();
}

@Override
public void onMapReady(GoogleMap googleMap) {

    googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

    mGoogleMap = googleMap;
    mGoogleMap.setMyLocationEnabled(true);

    buildGoogleApiClient();

    mGoogleApiClient.connect();


}

protected synchronized void buildGoogleApiClient() {
    Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
public void onConnected(Bundle bundle) {
    Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        //place marker at current position
        //mGoogleMap.clear();
        latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icongps));
        currLocationMarker = mGoogleMap.addMarker(markerOptions);
    }

    mLocationRequest = new LocationRequest();
    // mLocationRequest.setInterval(5000); //5 seconds
    // mLocationRequest.setFastestInterval(3000); //3 seconds
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    //mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);


}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(this, "onConnectionSuspended", Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Toast.makeText(this, "onConnectionFailed", Toast.LENGTH_SHORT).show();
}

@Override
public void onLocationChanged(Location location) {

    //place marker at current position
    //mGoogleMap.clear();
    if (currLocationMarker != null) {
        currLocationMarker.remove();
    }
    latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icontao));
    currLocationMarker = mGoogleMap.addMarker(markerOptions);

    //Toast.makeText(this,"Location Changed",Toast.LENGTH_SHORT).show();

    //zoom to current position:
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));

    //If you only need one location, unregister the listener
    //LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

}

}

php:

$strSQL ="SELECT * FROM `loc_info` WHERE name= 'Saverde Coffee Shop'";

$objQuery = mysqli_query($objConnect, $strSQL);
// or die (mysqli_error());
$arrRows = array();
$arryItem = array();


while($arr = mysqli_fetch_array($objQuery)){
$arryItem["location_id"] = $arr["location_id"];
$arryItem["latitude"] = $arr["latitude"];
$arryItem["longitude"] = $arr["longitude"];
$arryItem["name"] = $arr["name"];
$arrRows[]= $arryItem;

}


echo json_encode($arrRows);


?>
Meng
  • 123
  • 1
  • 3
  • 10

2 Answers2

1

If you got both points (Markers) where you want to draw the path then you have to draw PolliLines using your latlong. Below code will draw your path on map.

public void drawPath(String  result) {

try {
        //Tranform the string into a json object
       final JSONObject json = new JSONObject(result);
       JSONArray routeArray = json.getJSONArray("routes");
       JSONObject routes = routeArray.getJSONObject(0);
       JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
       String encodedString = overviewPolylines.getString("points");
       List<LatLng> list = decodePoly(encodedString);
       Polyline line = mMap.addPolyline(new PolylineOptions()
                                .addAll(list)
                                .width(12)
                                .color(Color.parseColor("#05b1fb"))//Google maps blue color
                                .geodesic(true)
                );

} 
catch (JSONException e) {

}
}    

Just follow the link. Answer : Draw path between two points using Google Maps Android API v2

Community
  • 1
  • 1
Awais
  • 1,157
  • 9
  • 15
0

You could use a Polyline. I have shared the links, the first one will give you a direct simple implementation. The other is to improve your understanding.

Polyline Implementation
Maps v2, Using Polyline

Community
  • 1
  • 1