두 개의 lat lng 지점 사이에 탐색 경로를 표시하고 싶습니다. 시작 위치는 현재 위치와 다를 수 있습니다. 나는이 일을 의도로하지만 나는 의도없이하고 싶다. Uber 택시와 같은 네비게이션 쇼. 나는 안드로이드에 새로 왔어. 제발 도와주세요. 미리 감사드립니다.내비게이션없이 Google지도의 두 Lat Lng 사이에 내비게이션을 표시하는 방법
0
A
답변
1
getDirectionsUrl (LatLng origin, LatLng dest) 함수에서 LatLan을 제공 할 수 있으며 origin과 dest 사이의 경로를 표시 할 수 있습니다.
XML 코드 :
<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" >
<RelativeLayout
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@mipmap/gradiant"
android:layout_alignParentTop="true"
android:padding="6dp">
<TextView
android:id="@+id/activity_registration_txtTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="16sp"
android:textStyle="bold"
android:text="Event Destination"/>
</RelativeLayout>
<fragment
android:id="@+id/map"
android:layout_below="@+id/header"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<TextView
android:id="@+id/tv_distance_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/header"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
자바 코드 :
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.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 com.mayur.aroundus.EventClass.Event;
import com.mayur.aroundus.Utility.CommonUtility;
import com.mayur.aroundus.Utility.DirectionsJSONParser;
import com.mayur.aroundus.Utility.GPSTracker;
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.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class MapsActivity extends Activity implements OnMapReadyCallback, com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener {
private static final String TAG ="AroundUs" ;
private GoogleMap mMap;
GPSTracker gps;
protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
private double latitude = 0;
private double longitude = 0;
List<Event> lsEvent=new ArrayList<Event>();
String destLatitude,destLongitude;
TextView tvDistanceDuration;
ArrayList<LatLng> markerPoints;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
GPSTracker gps = new GPSTracker(MapsActivity.this);
if(gps.canGetLocation()) {
System.out.println("Latitude = "+gps.getLatitude()+" Longitude = "+
gps.getLongitude());
}
markerPoints = new ArrayList<LatLng>();
Intent intent = getIntent();
destLatitude = intent.getStringExtra("Latitude");
destLongitude = intent.getStringExtra("Longitude");
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
//Runs when a GoogleApiClient object successfully connects.
@Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
latitude=mLastLocation.getLatitude();
longitude=mLastLocation.getLongitude();
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
tvDistanceDuration = (TextView) findViewById(R.id.tv_distance_time);
} else {
Toast.makeText(this, "no_location_detected", Toast.LENGTH_LONG).show();
}
}
@Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
@Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(latitude, longitude);
mMap.clear();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 16);
mMap.animateCamera(cameraUpdate);
System.out.println("Latitude "+latitude+ " \n Longitude "+longitude);
mMap.setMyLocationEnabled(true);
LatLng origin = new LatLng(latitude,longitude);
LatLng dest = new LatLng(Double.parseDouble(destLatitude),Double.parseDouble(destLongitude));
// 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 void call() {
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
LatLng origin = new LatLng(latitude,longitude);
LatLng dest = new LatLng(Double.parseDouble(destLatitude), Double.parseDouble(destLongitude));
// 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);
}
});
}
public String getLocationStringAddress(LatLng latLng){
Geocoder geocoder = new Geocoder(MapsActivity.this, Locale.getDefault());
String result = null;
try {
// latitude=23.0590869;
// longitude=72.5557736;
latitude=latLng.latitude;
longitude=latLng.longitude;
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
android.location.Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
// for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
// sb.append(address.getAddressLine(i)).append("\n");
// }
sb.append(address.getLocality()).append(", ");
// sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
}
return result;
}
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 downloading", 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();
String distance = "";
String duration = "";
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");
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(5);
lineOptions.color(Color.RED);
}
tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(destLatitude), Double.parseDouble(destLongitude)))
.title(getLocationStringAddress(new LatLng(Double.parseDouble(destLatitude), Double.parseDouble(destLongitude))))
// .snippet(getLocationStringAddress(new LatLng(Double.parseDouble(destLatitude), Double.parseDouble(destLongitude))))
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_set_marker)));
}
}
}
0
내가 여기
public void markRoute(LatLng... value){
LatLng startPoint = value[0];
LatLng endPoint = value[1];
LatLng midPoint = value[2];
String url = "";
if(midPoint != null)
url = "https://maps.googleapis.com/maps/api/directions/" +
"json?origin="+startPoint.latitude+","+startPoint.longitude+"&destination="+endPoint.latitude+","+endPoint.longitude+"&" +
"waypoints="+midPoint.latitude+","+midPoint.longitude;
else
url = "https://maps.googleapis.com/maps/api/directions/" +
"json?origin="+startPoint.latitude+","+startPoint.longitude+"&destination="+endPoint.latitude+","+endPoint.longitude;
StringRequest stringRequest = new StringRequest(Request.Method.POST,url ,
new Response.Listener<String>() {
@Override
public void onResponse(String result) {
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(result);
JSONArray routes = jsonResponse.getJSONArray("routes");
for (int i=0; i<routes.length(); i++) {
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
JSONArray legs = routes.getJSONObject(i).getJSONArray("legs");
for (int j=0; j<legs.length(); j++) {
JSONArray steps = legs.getJSONObject(j).getJSONArray("steps");
int lastItem = 0;
for (int k=0; k<steps.length(); k++) {
options.add(new LatLng(steps.getJSONObject(k).getJSONObject("start_location").getDouble("lat"),
steps.getJSONObject(k).getJSONObject("start_location").getDouble("lng")));
lastItem = k;
}
options.add(new LatLng(steps.getJSONObject(lastItem).getJSONObject("end_location").getDouble("lat"),
steps.getJSONObject(lastItem).getJSONObject("end_location").getDouble("lng")));
}
mMap.addPolyline(options);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
mMap
가 목적지에 원점에서 경로에 폴리 라인을 그릴 수있는 단 하나의 연료 소모량을했다 GoogleMap
,받는 사람 onMapReady()
단일 웨이 포인트 또는 중간 점이 제공되면이 함수를 호출 할 수 있습니다. 단지 소스와 목적지가 어디서든 프로그램에서
markRoute(LatLng startPoint, LatLng endPoint)
를 제공하는 경우로
markRoute(LatLng startPoint, LatLng endPoint, LatLng midPoint)
나 또한 할 수있다.
관련 문제
- 1. 대신 Google지도의 Lat 및 Lng API
- 2. lat lng 값을 디코드하십시오.
- 3. GeoCoordinate lat + lng 값을 동적으로 설정하는 방법
- 4. 동일한 lat/lng gmap v3
- 5. 여분의 번들로 lng/lat 전달하기
- 6. 지도 iPhone에서 내비게이션을 표시하는 방법?
- 7. Jquery var 구문입니다. 두 개의 변수로 쪼개기 Lat, Lng
- 8. android에서 내비게이션을 차례로 표시하는 방법
- 9. google maps mysql lat lng to javascript
- 10. Google지도는 실내 건물을 가져옵니다. lat lng
- 11. 데이터베이스 주소를 lat/lng json으로 변환
- 12. Google지도 V3에서 마커의 lat-lng 수정
- 13. 어레이를 Google Lat/Lng Array로 변환 하시겠습니까?
- 14. 업데이트 google maps lat/lng 데이터베이스에
- 15. Google Places API 결과 0,0 Lat Lng
- 16. lat, lng 쌍 주위에서 직교 좌표를 얻으십시오.
- 17. XML 파일에서 MapQuest에 lng 및 lat 좌표로드
- 18. backround에서 lat lng 값을 매 1 분마다 끊는 방법?
- 19. 웹 앱에서 Google지도의 방문자 위치를 표시하는 방법
- 20. 같은 줄에 페이지 머리글과 내비게이션을 표시하는 방법
- 21. Google지도의 두 지점 사이에 탐색기를 사용하는 방법은 무엇입니까?
- 22. 지도에서 내비게이션을 처리하는 방법
- 23. 지오 코더 json 결과에서 lat, lng 가져 오기
- 24. MongoDB - 다각형의 Lng/Lat 인 경우, 문서 반환
- 25. 사용자 위치 가져 오기 GPS 및 네트워크를 사용하는 LAT LNG
- 26. MySQL 열 POINT 대 2x DECIMAL (lat & lng) 성능
- 27. Google지도는 lat-lng 경계 상자 좌표를 통해 요청합니다.
- 28. 결과가 균등하게 분포 된 MySQL Lat/Lng 경계
- 29. 다각형 점을 그릴 때 lat lng 가져 오기
- 30. 제출하기 전에 Lat Lng 값을 숨겨진 필드로 설정하기