使用Androids Google Maps API查找路线

使用Androids Google Maps API查找路线,第1张

概述我希望能够使用适用于 Android的Google Maps API在两个用户定义的地理点之间显示路线.我还希望能够让用户选择要显示的路线类型,无论是步行,骑车,汽车等.此外,我希望能够计算使用此路线所需的时间和距离.我试过在网上搜索并查看其他stackoverflow问题,但无济于事.我怎么会这样呢?我怎么能编码这个. // – – 编辑 – – // 我还想得到交通信息,如繁忙的路线,拥堵等. 我希望能够使用适用于 Android的Google Maps API在两个用户定义的地理点之间显示路线.我还希望能够让用户选择要显示的路线类型,无论是步行,骑车,汽车等.此外,我希望能够计算使用此路线所需的时间和距离.我试过在网上搜索并查看其他stackoverflow问题,但无济于事.我怎么会这样呢?我怎么能编码这个.

// – – 编辑 – – //

我还想得到交通信息,如繁忙的路线,拥堵等.

解决方法 使用Wrapper库的AndroID Google Maps Routing示例代码

使用AndroID Studio Gradle条目:

compile 'com.github.jd-alexander:library:1.1.0'

MainActivity.java

import androID.Manifest;import androID.content.pm.PackageManager;import androID.graphics.color;import androID.location.Location;import androID.location.LocationListener;import androID.location.LocationManager;import androID.support.design.Widget.floatingActionbutton;import androID.support.design.Widget.Snackbar;import androID.support.v4.app.ActivityCompat;import androID.support.v4.app.FragmentActivity;import androID.os.Bundle;import androID.vIEw.VIEw;import androID.Widget.TextVIEw;import androID.Widget.Toast;import com.directions.route.Route;import com.directions.route.RouteException;import com.directions.route.Routing;import com.directions.route.RoutingListener;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.LatLngBounds;import com.Google.androID.gms.maps.model.Marker;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 java.util.ArrayList;import java.util.Iterator;import java.util.List;public class MainActivity extends FragmentActivity implements OnMapReadyCallback,LocationListener,GoogleMap.OnMarkerClickListener,RoutingListener {    private GoogleMap mMap = null;    private LocationManager locationManager = null;    private floatingActionbutton fab = null;    private TextVIEw txtdistance,txtTime;    //Global UI Map markers    private Marker currentMarker = null;    private Marker destMarker = null;    private LatLng currentLatLng = null;    private polyline line = null;    //Global flags    private boolean firstRefresh = true;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_map);        Constants.POINT_DEST = new LatLng(18.758663,73.382025);        //Lonavala destination.        //Load the map fragment on UI        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentByID(R.ID.map);        mapFragment.getMapAsync(this);        txtdistance = (TextVIEw)findVIEwByID(R.ID.txt_distance);        txtTime = (TextVIEw)findVIEwByID(R.ID.txt_time);        fab = (floatingActionbutton)findVIEwByID(R.ID.fab);        fab.setonClickListener(new VIEw.OnClickListener() {            @OverrIDe            public voID onClick(VIEw v) {                MainActivity.this.getRoutingPath();                Snackbar.make(v,"Fetching Route",Snackbar.LENGTH_SHORT).show();            }        });    }    @OverrIDe    protected voID onResume() {        super.onResume();        firstRefresh = true;        //Ensure the GPS is ON and location permission enabled for the application.        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);        if (!PermissionCheck.getInstance().checkGPSPermission(this,locationManager)) {            //GPS not enabled for the application.        } else if (!PermissionCheck.getInstance().checkLocationPermission(this)) {            //Location permission not given.        } else {            Toast.makeText(MainActivity.this,"Fetching Location",Toast.LENGTH_SHORT).show();            try {                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,this);                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,5000,this);            } catch(Exception e)            {                Toast.makeText(MainActivity.this,"ERROR: Cannot start location Listener",Toast.LENGTH_SHORT).show();            }        }    }    @OverrIDe    protected voID onPause() {        if (locationManager != null) {            //Check needed in case of  API level 23.            if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {            }            try {                locationManager.removeUpdates(this);            } catch (Exception e) {            }        }        locationManager = null;        super.onPause();    }    @OverrIDe    protected voID onStop() {        super.onStop();    }    @OverrIDe    public voID onMapReady(GoogleMap GoogleMap)    {        mMap = GoogleMap;        //mMap.getUiSettings().setZoomControlsEnabled(true);        mMap.getUiSettings().setCompassEnabled(true);        mMap.getUiSettings().setAllGesturesEnabled(true);        mMap.setonMarkerClickListener(this);    }    /**     * @desc LocationListener Interface Methods implemented.     */    @OverrIDe    public voID onLocationChanged(Location location)    {        double lat = location.getLatitude();        double lng = location.getLongitude();        currentLatLng = new LatLng(lat,lng);        if(firstRefresh)        {            //Add Start Marker.            currentMarker = mMap.addMarker(new MarkerOptions().position(currentLatLng).Title("Current position"));//.icon(BitmapDescriptorFactory.fromresource(R.drawable.location)));            firstRefresh = false;            destMarker = mMap.addMarker(new MarkerOptions().position(Constants.POINT_DEST).Title("Destination"));//.icon(BitmapDescriptorFactory.fromresource(R.drawable.location)));            mMap.moveCamera(CameraUpdateFactory.newLatLng(Constants.POINT_DEST));            mMap.animateCamera(CameraUpdateFactory.zoomTo(15));            getRoutingPath();        }        else        {            currentMarker.setposition(currentLatLng);        }    }    @OverrIDe    public voID onStatusChanged(String provIDer,int status,Bundle extras) {}    @OverrIDe    public voID onProvIDerEnabled(String provIDer) {}    @OverrIDe    public voID onProvIDerDisabled(String provIDer) {}    /**     * @desc MapMarker Interface Methods Implemented.     */    @OverrIDe    public boolean onMarkerClick(Marker marker)    {        if(marker.getTitle().contains("Destination"))        {            //Do some task on dest pin click        }        else if(marker.getTitle().contains("Current"))        {            //Do some task on current pin click        }        return false;    }    /**     *@desc Routing Listener interface methods implemented.     **/    @OverrIDe    public voID onRoutingFailure(RouteException e)    {        Toast.makeText(MainActivity.this,"Routing Failed",Toast.LENGTH_SHORT).show();    }    @OverrIDe    public voID onRoutingStart() { }    @OverrIDe    public voID onRoutingSuccess(ArrayList<Route> List,int i)    {        try        {            //Get all points and plot the polyline route.            List<LatLng> ListPoints = List.get(0).getPoints();            polylineoptions options = new polylineoptions().wIDth(5).color(color.BLUE).geodesic(true);            Iterator<LatLng> iterator = ListPoints.iterator();            while(iterator.hasNext())            {                LatLng data = iterator.next();                options.add(data);            }            //If line not null then remove old polyline routing.            if(line != null)            {                line.remove();            }            line = mMap.addpolyline(options);            //Show distance and duration.            txtdistance.setText("distance: " + List.get(0).getdistanceText());            txtTime.setText("Duration: " + List.get(0).getDurationText());            //Focus on map bounds            mMap.moveCamera(CameraUpdateFactory.newLatLng(List.get(0).getLatLgnBounds().getCenter()));            LatLngBounds.Builder builder = new LatLngBounds.Builder();            builder.include(currentLatLng);            builder.include(Constants.POINT_DEST);            LatLngBounds bounds = builder.build();            mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,50));        }        catch (Exception e)         {            Toast.makeText(MainActivity.this,"EXCEPTION: Cannot parse routing response",Toast.LENGTH_SHORT).show();        }    }    @OverrIDe    public voID onRoutingCancelled()     {        Toast.makeText(MainActivity.this,"Routing Cancelled",Toast.LENGTH_SHORT).show();    }    /**     * @method getRoutingPath     * @desc Method to draw the Google routed path.     */    private voID getRoutingPath()    {        try        {            //Do Routing            Routing routing = new Routing.Builder()                    .travelMode(Routing.TravelMode.DRIVING)                    .withListener(this)                    .waypoints(currentLatLng,Constants.POINT_DEST)                    .build();            routing.execute();        }        catch (Exception e)        {            Toast.makeText(MainActivity.this,"Unable to Route",Toast.LENGTH_SHORT).show();        }    }}

Constants.java

/** * @class Constants * @desc Constant class for holding values at runtime. */public class Constants{    //Map LatLong points    public static LatLng POINT_DEST = null;}

activity_map.xml

<androID.support.design.Widget.CoordinatorLayoutxmlns:androID="http://schemas.androID.com/apk/res/androID"xmlns:app="http://schemas.androID.com/apk/res-auto"xmlns:map="http://schemas.androID.com/apk/res-auto"xmlns:tools="http://schemas.androID.com/tools"androID:layout_wIDth="match_parent"androID:layout_height="match_parent"><linearLayout androID:layout_wIDth="match_parent"    androID:layout_height="match_parent"    androID:orIEntation="vertical">    <linearLayout        androID:ID="@+ID/vIEwA"        androID:layout_wIDth="match_parent"        androID:layout_height="match_parent"        androID:layout_weight="0.1"        androID:orIEntation="horizontal">        <fragment            androID:ID="@+ID/map"            androID:name="com.Google.androID.gms.maps.SupportMapFragment"            androID:layout_wIDth="match_parent"            androID:layout_height="match_parent"            tools:context="com.packagename.MainActivity" />    </linearLayout>    <linearLayout        androID:ID="@+ID/vIEwB"        androID:layout_wIDth="match_parent"        androID:layout_height="match_parent"        androID:layout_weight="0.9"        androID:gravity="center|left"        androID:paddingleft="20dp"        androID:background="#FFFFFF"        androID:orIEntation="vertical" >        <TextVIEw            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:textSize="16dp"            androID:text="distance ?"            androID:paddingtop="3dp"            androID:paddingleft="3dp"            androID:paddingBottom="3dp"            androID:ID="@+ID/txt_distance" />        <TextVIEw            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:textSize="17dp"            androID:paddingleft="3dp"            androID:text="Duration ?"            androID:ID="@+ID/txt_time" />    </linearLayout></linearLayout><androID.support.design.Widget.floatingActionbutton    androID:ID="@+ID/fab"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:layout_margin="16dp"    androID:clickable="true"    androID:src="@androID:drawable/ic_dialog_map"    app:layout_anchor="@ID/vIEwA"    app:layout_anchorGravity="bottom|right|end"/></androID.support.design.Widget.CoordinatorLayout>
总结

以上是内存溢出为你收集整理的使用Androids Google Maps API查找路线全部内容,希望文章能够帮你解决使用Androids Google Maps API查找路线所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1137392.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存