Android 如何确定从我的位置到任何标记的驾驶路线
我是编程的初学者。 我得到了一条从我所在地到目的地的驾驶路线。但是这些教程并不是我想要的 链接教程: 问题是如何获得从我所在位置到自定义标记的驾驶路线Android 如何确定从我的位置到任何标记的驾驶路线,android,google-maps-markers,google-maps-android-api-2,google-maps-api-2,android-maps-v2,Android,Google Maps Markers,Google Maps Android Api 2,Google Maps Api 2,Android Maps V2,我是编程的初学者。 我得到了一条从我所在地到目的地的驾驶路线。但是这些教程并不是我想要的 链接教程: 问题是如何获得从我所在位置到自定义标记的驾驶路线 GoogleMap map; ArrayList<LatLng> mMarkerPoints; double mLatitude=0; double mLongitude=0; TextView tvDistanceDuration; @Override protected void onCreate(Bundle savedIn
GoogleMap map;
ArrayList<LatLng> mMarkerPoints;
double mLatitude=0;
double mLongitude=0;
TextView tvDistanceDuration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
tvDistanceDuration = (TextView) findViewById(R.id.tv_distance_time);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Initializing
mMarkerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
map = fm.getMap();
// Enable MyLocation Button in the Map
map.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
// Setting onclick event listener for the map
map.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
// Already map contain destination location
if(mMarkerPoints.size()>=1){
FragmentManager fm = getSupportFragmentManager();
mMarkerPoints.clear();
map.clear();
LatLng startPoint = new LatLng(mLatitude, mLongitude);
// draw the marker at the current position
drawMarker(startPoint);
}
// draws the marker at the currently touched location
drawMarker(mMarkerPoints.get(1));
// Checks, whether start and end locations are captured
if(mMarkerPoints.size() >= 1){
LatLng origin = mMarkerPoints.get(0);
LatLng dest = mMarkerPoints.get(1);
// 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;
}
/** A class to download data from Google Directions URL */
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 Directions 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(2);
lineOptions.color(Color.RED);
}
tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
@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;
}
private void drawMarker(LatLng point){
mMarkerPoints.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.
*/
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(-6.381407, 106.855766))
.title("PT. Andalan Sumber Rezeki").snippet("Jln. Ir. H. Juanda, Kp. Bojong RT. 03/06 Kel. Batik Jaya <br/> Kec. Sukma Jaya DEPOK <br/> Phone : 0813 814 77771"));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(-6.361964, 106.775808))
.title("PT. Solia Mitra Motor").snippet("Jln. Limo Raya No.5 Cinere Depok <br/> Phone : 0217540506"));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(-6.3845335,106.8285415))
.title("Mahkota Depok")
.snippet("Jln. Raya Margonda No.209 <br/> Phone : 02177210208"));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(-6.111662, 106.911759))
.title("Mahkota Arif Rahman Hakim").snippet("Jln. Arif Rahman Hakim No.78 <br/> phone : 02177202260"));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(-6.451293, 106.798896))
.title("PT.Suzuki Citayam").snippet("Jln. Pabuaran Raya No.44-46 Kampung Pintu Air Pabuaran <br/> phone : 02187990951"));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(-6.383348, 106.814409))
.title("PT. Singgalang Motor").snippet("Jln. Nusantara Raya Depok <br/> phone : 021 77212827"));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(-6.401883, 106.836572))
.title("PT. Galaxy Prima Depok").snippet("Jln. Kemakmuran Raya No.50 <br/> phone : 02177825282"));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(-6.3901018,106.8268545))
.title("PT. Suzuki SEM Depok").snippet("Jln. Margonda Raya No.27 <br/> phone : 0217764887"));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(-6.391512, 106.851940))
.title("Suzuki DIPA Motor").snippet("<p>" +"Jln. Kejayaan Raya" + "<br/> " + "phone : 021 77831015"));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(-6.3901018,106.8268545))
.title("PT. Tugu Gema Motorindo").snippet("Jln. Akses UI No. 25 <br/> phone : (021) 8701111, (021) 8702222"));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(-6.3590335,106.8586754))
.title("PT. Restu Mahkota Karya").snippet("Jl. Raya Bogor Km,29 No.18 Cimanggis <br/> phone : 021 87708918"));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(-6.3779722,106.8650424))
.title("Suzuki Cisalak").snippet("Jalan Raya Bogor KM.31 <br/> phone : 021 8722624"));
}
@Override
public void onLocationChanged(Location location) {
// Draw the marker, if destination location is not set
if(mMarkerPoints.size() < 2){
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng point = new LatLng(mLatitude, mLongitude);
map.moveCamera(CameraUpdateFactory.newLatLng(point));
map.animateCamera(CameraUpdateFactory.zoomTo(12));
drawMarker(point);
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
GoogleMap;
ArrayList mMarkerPoints;
双梯度=0;
双倍长度=0;
文本视图tvdestanceduration;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
tvdanceduration=(TextView)findViewById(R.id.tv\u distance\u time);
//获取Google Play可用性状态
int status=GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
如果(status!=ConnectionResult.SUCCESS){//Google Play服务不可用
int requestCode=10;
Dialog Dialog=GooglePlayServicesUtil.getErrorDialog(状态、此、请求代码);
dialog.show();
}其他{//Google Play服务可用
//初始化
mMarkerPoints=newarraylist();
//获取对活动\u main的SupportMapFragment的引用
SupportMapFragment fm=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
//正在获取SupportMapFragment的映射
map=fm.getMap();
//在地图中启用MyLocation按钮
map.setMyLocationEnabled(true);
//从系统服务位置\u服务获取LocationManager对象
LocationManager LocationManager=(LocationManager)getSystemService(LOCATION\u服务);
//创建条件对象以检索提供程序
标准=新标准();
//获取最佳提供商的名称
字符串提供程序=locationManager.getBestProvider(条件为true);
//从GPS获取当前位置
Location Location=locationManager.getLastKnownLocation(提供者);
如果(位置!=null){
onLocationChanged(位置);
}
locationManager.RequestLocationUpdate(提供程序,20000,0,此);
//为映射设置onclick事件侦听器
setOnMapClickListener(新的OnMapClickListener(){
@凌驾
公共空区(停车点){
//地图已包含目标位置
如果(mMarkerPoints.size()>=1){
FragmentManager fm=getSupportFragmentManager();
mMarkerPoints.clear();
map.clear();
LatLng startPoint=新LatLng(高度、长度);
//在当前位置绘制标记
绘图标记(起点);
}
//在当前接触的位置绘制标记
drawMarker(mMarkerPoints.get(1));
//检查是否捕获开始和结束位置
如果(mMarkerPoints.size()>=1){
LatLng origin=mMarkerPoints.get(0);
LatLng dest=mMarkerPoints.get(1);
//获取Google Directions API的URL
字符串url=getDirectionsUrl(源、目标);
DownloadTask DownloadTask=新的DownloadTask();
//开始从Google Directions API下载json数据
downloadTask.execute(url);
}
}
});
}
}
私有字符串getDirectionsUrl(LatLng来源,LatLng目的地){
//路线起点
字符串str_origin=“origin=“+origin.latitude+”,“+origin.longitude;
//路线目的地
字符串str_dest=“destination=”+dest.latitude+”,“+dest.longitude;
//传感器启用
字符串sensor=“sensor=false”;
//为web服务构建参数
字符串参数=str_origin+“&”+str_dest+“&”+传感器;
//输出格式
字符串输出=“json”;
//构建web服务的url
字符串url=”https://maps.googleapis.com/maps/api/directions/“+输出+”?“+参数;
返回url;
}
/**从url下载json数据的方法*/
私有字符串下载URL(字符串strUrl)引发IOException{
字符串数据=”;
InputStream iStream=null;
HttpURLConnection-urlConnection=null;
试一试{
URL=新URL(strUrl);
//创建http连接以与url通信
urlConnection=(HttpURLConnection)url.openConnection();
//连接到url
urlConnection.connect();
//从url读取数据
iStream=urlConnection.getInputStream();
BufferedReader br=新的BufferedReader(新的InputStreamReader(iStream));
StringBuffer sb=新的StringBuffer();
字符串行=”;
而((line=br.readLine())!=null){
某人附加(行);
}
data=sb.toString();
br.close();
}捕获(例外e){
Log.d(“下载url时出现异常”,例如toString());
}最后{
iStream.close();
urlConnection.disconnect();
}
返回数据;
}
/**从Google Directions URL下载数据的类*/
私有类DownloadTask扩展了AsyncTask{
//在非ui线程中下载数据
@凌驾
受保护的字符串doInBackground(字符串…url){
//用于存储来自web服务的数据
字符串数据=”;
试一试{
//从web服务获取数据
数据=下载url(url[0]);
}捕获(例外e){
Log.d(“后台任务”,例如toString());
}
返回数据;
}
//在UI线程中执行,在
//doInBackground()
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
ParserTask ParserTask=新的ParserTask();
//调用线程以解析JSON数据
执行(结果);
}
}
/**上课
String uri = "http://maps.google.com/maps?f=d&hl=es&saddr="+startingLatitude+","+startingLongitude+"&daddr="+endingLatitude+","+endingLongitude;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
private static ArrayList<LatLng> getRoutePoints(String url) {
JSONObject dirJson = Json.getJson(url);
if (dirJson != null) {
try {
ArrayList<LatLng> routeLine = decodeOverviewPolyline(dirJson
.getJSONArray("routes").getJSONObject(0)
.getJSONObject("overview_polyline").getString("points"));
if (routeLine != null & routeLine.size() > 0)
return routeLine;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
private static ArrayList<LatLng> decodeOverviewPolyline(String encoded) {
ArrayList<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;
}