简体   繁体   English

通过URL在Google Maps Fragment上绘制路线

[英]Plot Route on Google Maps Fragment via URL

So I have looked around for examples of plotting routes on Google maps. 因此,我到处寻找在Google地图上绘制路线的示例。 However, my obstacle is that I have to go to url/route.coords in order to get the lat and lng for the route. 但是,我的障碍是我必须去url / route.coords才能获得路线的经纬度。 When I go to that url manually it downloads a text file with all the route information. 当我手动转到该URL时,它将下载包含所有路线信息的文本文件。 So if anyone could help me as to where to start that would be greatly appreciated. 因此,如果有人可以帮助我从哪里开始,那将不胜感激。 I already have the map showing along with a dot for your current location along with some other classes outlined. 我已经在地图上显示了您当前位置的点以及概述的其他一些类别。 My end goal is to plot a different colored route for every drive, each drive has their specific URL. 我的最终目标是为每个驱动器绘制不同的彩色路线,每个驱动器都有其特定的URL。

Fragment for where I am showing my Google Maps: 显示我的Google地图的片段:

public class ThirdFragment extends Fragment implements OnMapReadyCallback {
    View myView;
    private GoogleMap mMap;
    MapFragment mapFrag;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.third_layout, container, false);
        return myView;

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mapFrag = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
        //mapFrag.onResume();

    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;


        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
            Criteria criteria = new Criteria();
            LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
            String provider = locationManager.getBestProvider(criteria, false);
            Location location = locationManager.getLastKnownLocation(provider);
            double lat =  location.getLatitude();
            double lng = location.getLongitude();
            LatLng coordinate = new LatLng(lat, lng);
            CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 13);
            mMap.animateCamera(yourLocation);

        } else {
            final AlertDialog alertDialogGPS = new AlertDialog.Builder(getActivity()).create();

            alertDialogGPS.setTitle("Info");
            alertDialogGPS.setMessage("Looks like you have not given GPS permissions. Please give GPS permissions and return back to the app.");
            alertDialogGPS.setIcon(android.R.drawable.ic_dialog_alert);
            alertDialogGPS.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    Intent intentSettings = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
                    startActivity(intentSettings);
                    alertDialogGPS.dismiss();
                }

            });

            alertDialogGPS.show();
        }

    }
    @Override
    public void onResume() {
        super.onResume();
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            mapFrag.getMapAsync(this);
        }
        else {
        }
    }
}

RouteCoord.java RouteCoord.java

public class RouteCoord {
    private String lat, dist, lng, speed, index;
    public String getLat() {
        return lat;
    }

    public void setLat(String lat) {this.lat = lat;}

    public String getLng(){return lng;}

    public void setLng(String lng) {this.lng = lng;}
}

RouteAdapter.java RouteAdapter.java

public class RouteAdapter extends ArrayAdapter<Map.Entry> {

    private final Activity context;
    // you may need to change List to something else (whatever is returned from drives.entrySet())
    private final List<Map.Entry> drives;
    public static String DriveURL;
    public static String routeLat;
    public static String routeLng;


    SharedPreferences sharedPref;
    // may also need to change List here (above comment)
    public RouteAdapter(Activity context, List<Map.Entry> drives) {
        super(context, R.layout.drive_url_list, drives);
        this.context = context;
        this.drives = drives;
        sharedPref = context.getPreferences(Context.MODE_PRIVATE);
    }


    @Override
    public View getView(int position, View view, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView = inflater.inflate(R.layout.third_layout, null, true);

        Map.Entry drive = this.drives.get(position);

        // position is the index of the drives.entrySet() array
        int driveNum = position + 1;

        // need to import your Route class
        Route route = (Route) drive.getValue();
        RouteCoord routeCoord = (RouteCoord) drive.getValue();
        routeLat = routeCoord.getLat();
        routeLng = routeCoord.getLng();

        // need to import your URL class
        DriveURL = route.getUrl();

        return rowView;
    }
}

You need to draw a Polyline on the Google Map using the coordinates of the route. 您需要使用路线的坐标在Google地图上绘制一条折线

See below sample code: 参见下面的示例代码:

/**
 * To show map with this activity add ORIGIN, DESTINATION lat double arrays in
 * intent.
 * 
 * </br> For specifying origin, put latitude and longitude in an array of double
 * with key = {@link #ORIGIN} in the intent </br >For specifying destination,
 * put latitude and longitude in an array of double with key =
 * {@link #DESTINATION} in the intent
 * 
 * @author Shridutt.Kothari
 * 
 */
public class MapsActivity extends BaseActivity {

    private static final String TAG = "MapsActivity";

    /**
     * String key for specifying array of long containing origin latitude and
     * longitude .
     */
    public static final String ORIGIN = "ORIGIN";
    private double[] destinationLocation;
    private GoogleMap map;
    private PathUpdateReceiver pathUpdateReceiver;
    private PolylineOptions lineOptions;
    private Marker marker;
    private MarkerOptions ambulanceMarkerOption;
    private Polyline polyline;
    private List<LatLng> points;
    private static final int ZOOM_LEVEL = 15;
    private static final int POLYLINE_WIDTH = 5;
    private static final String AMBULANCE_MARKER_NAME = "Ambulance";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        // Intent launchIntent = getIntent();
        // originLocation = new double[2];
        // originLocation = launchIntent.getDoubleArrayExtra(ORIGIN);
        // originLocation[0] = 28.628525;
        // originLocation[1] = 77.22219016666666;
        destinationLocation = new double[2];

        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();
        if (null == map) {
            try {
                MapsInitializer.initialize(getApplicationContext());
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                        "Google play services not available, can't show map!",
                        Toast.LENGTH_LONG).show();
                e.printStackTrace();
                this.finish();
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null == pathUpdateReceiver) {
            pathUpdateReceiver = new PathUpdateReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConstants.VEHICLE_DATA_SAMPLE_ID);
        registerReceiver(pathUpdateReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(pathUpdateReceiver);
    }

    /**
     * PathUpdate
     * 
     *  
     */
    private class PathUpdateReceiver extends BroadcastReceiver {        

        @Override
        public void onReceive(Context context, Intent intent) {
            if (map != null
                    && intent.getAction().equalsIgnoreCase(
                            AppConstants.VEHICLE_DATA_SAMPLE_ID)) {
                map.getUiSettings().setZoomControlsEnabled(true);
                map.getUiSettings().setTiltGesturesEnabled(true);
                map.getUiSettings().setAllGesturesEnabled(true);

                VehicleDataSample vehicleDataSample = ((GoldenHourTrackerApp) getApplication()).getVehicleDataSample();
                destinationLocation[0] = vehicleDataSample.getLatitude();
                destinationLocation[1] = vehicleDataSample.getLongitude();

                Log.e(TAG, "received location update:"+destinationLocation[0]+", "+destinationLocation[1]);
                LatLng newPoint = new LatLng(destinationLocation[0],
                        destinationLocation[1]);
                if (null != destinationLocation) {
                    map.setTrafficEnabled(false);
                    map.setBuildingsEnabled(true);
                    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                    LatLng originlatlng = new LatLng(destinationLocation[0],
                            destinationLocation[1]);
                    map.moveCamera(CameraUpdateFactory.newLatLngZoom(
                            originlatlng, ZOOM_LEVEL));
                    -@SuppressWarnings("unused")
                    MarkerOptions traumaLoacationMarkerOption = new MarkerOptions()
                            .position(originlatlng)
                            .title(TRAUMA_LOCATION_MARKER_NAME)
                            .icon(BitmapDescriptorFactory
                                    .defaultMarker(BitmapDescriptorFactory.HUE_RED));
                    if (ambulanceMarkerOption == null) {
                        ambulanceMarkerOption = new MarkerOptions()
                                .position(originlatlng)
                                .title(AMBULANCE_MARKER_NAME)
                                .icon(BitmapDescriptorFactory
                                        .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                        // TODO: Currently Not adding
                        // TRAUMA_LOCATION_MARKER_NAME on Map
                        // map.addMarker(traumaLoacationMarkerOption);
                        marker = map.addMarker(ambulanceMarkerOption);
                        marker.showInfoWindow();
                    }

                    if (null == lineOptions) {
                        lineOptions = new PolylineOptions();
                        lineOptions.add(newPoint);
                        // A 5 width Polyline
                        lineOptions.width(POLYLINE_WIDTH);
                        lineOptions.color(context.getResources().getColor(
                                R.color.blue));
                        polyline = map.addPolyline(lineOptions);
                    }

                    marker.setPosition(newPoint);
                    marker.setVisible(true);
                    marker.showInfoWindow();
                    map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                            newPoint, ZOOM_LEVEL));
                    points = polyline.getPoints();
                    points.add(newPoint);
                    polyline.setPoints(points);
                }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM