开发者

Draw the route between 2 overlays

开发者 https://www.devze.com 2023-03-11 21:50 出处:网络
In my app I displayed on map 2 locations and I marked them with a marker. Now, I want to draw the route between them,and I don\'t know how can I do this. How should my function draw look like?

In my app I displayed on map 2 locations and I marked them with a marker. Now, I want to draw the route between them,and I don't know how can I do this. How should my function draw look like?

This is my code:

package com.ShoppingList.Maps;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;

import com.ShoppingList.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;

import java.util.ArrayList;
import java.util.List;

public class OnMap extends MapActivity {
    private MapView map = null;
    private MyLocationOverlay me = null;
    //private myOverlay m = null;

    double latitudine;
    double longitudine;

    double latshop;
    double longshop;

    String nameshop;

    Canvas canvas = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shopsonmap);

        map = (MapView) findViewById(R.id.shopsonmap);

        latitudine = getIntent().getDoubleExtra("latcurent", 0);
        longitudine = getIntent().getDoubleExtra("longcurent", 0);
        latshop = getIntent().getDoubleExtra("latshop", 0);
        longshop = getIntent().getDoubleExtra("longshop", 0);
        nameshop = getIntent().getStringExtra("nameshop");

        GeoPoint p1 = new GeoPoint((int) latitudine, (int) longitudine);
        GeoPoint p2 = new GeoPoint((int) latshop, (int) longshop);

        map.getController().setCenter(getPoint(latitudine, longitudine));
        map.getController().setZoom(15);
        map.setBuiltInZoomControls(true);
        map.setSatellite(false);
        map.setStreetView(true);
        map.invalidate();

        Drawable marker = getResources().getDrawable(R.drawable.marker);

        marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
                .getIntrinsicHeight());

        map.getOverlays().add(new SitesOverlay(marker));

        me = new MyLocationOverlay(this, map);
        map.getOverlays().add(me);


    }

    /*class myOverlay extends Overlay {
        GeoPoint gp1;
        GeoPoint gp2;

        public myOverlay(GeoPoint gp1, GeoPoint gp2) {

            this.gp1 = gp1;
            this.gp2 = gp2;

        }

        public void draw(Canvas canvas, MapView mapView, boolean shadow) {

            Projection projection = mapView.getProjection();
            Paint mPaint = new Paint();
            Point from = new Point();
            projection.toPixels(gp1, from);
            mPaint.setColor(Color.BLUE);

            Point to = new Point();
            projection.toPixels(gp2, to);
    开发者_如何转开发        mPaint.setStrokeWidth(9);
            mPaint.setAlpha(120);
            canvas.drawLine(from.x, from.y, to.x, to.y, mPaint);
            super.draw(canvas, mapView, shadow);

        }
    }*/

    @Override
    public void onResume() {
        super.onResume();

        me.enableCompass();
    }

    @Override
    public void onPause() {
        super.onPause();

        me.disableCompass();
    }

    @Override
    protected boolean isRouteDisplayed() {
        return (false);
    }

    private GeoPoint getPoint(double lat, double lon) {
        return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
    }

    private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
        private List<OverlayItem> items = new ArrayList<OverlayItem>();
        private Drawable marker = null;

        public SitesOverlay(Drawable marker) {
            super(marker);
            this.marker = marker;

            items.add(new OverlayItem(getPoint(latitudine, longitudine),
                    "Your location", "You are here!"));

            items.add(new OverlayItem(getPoint(latshop, longshop), "The shop",
                    "The shop " + nameshop + " is here"));

            populate();
        }

        @Override
        protected OverlayItem createItem(int i) {
            return (items.get(i));
        }

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {

            super.draw(canvas, mapView, shadow);

            boundCenterBottom(marker);
        }

        @Override
        protected boolean onTap(int i) {
            Toast.makeText(OnMap.this, items.get(i).getSnippet(),
                    Toast.LENGTH_SHORT).show();

            return (true);
        }

        @Override
        public int size() {
            return (items.size());
        }
    }
}

Thanks..


So let's suppose you are obtaining the locations (in JSON) from a REST web service. For this, I used Volley library to connect and obtain the response from the server.

Example of JSONArray response:

[ {...,"location":"44.924654,8.586219", ...}, {...,"location":"44.906177,8.157752", ...}, {...,"location":"44.906177,8.157752", ...}, {..., "location": "44.956733,7.876227", ...}, {..., "location": "45.034424,7.671607", ...} ]

The step would be to set the first and the last locations as the markers, and the intermediate locations will draw the line between them.

Because location is obtained as a string, we have first to split the string and assign the part before the "," to the latitude and the rest as longitude.

                    public void onResponse(JSONArray response) {

                    if (response.length() > 0) {
                        try {
                            //creating the markers: for this I need the first and the last location
                            JSONObject firstLocationJson = response.getJSONObject(0);
                            JSONObject lastLocationJson = response.getJSONObject(response.length() - 1);

                            String[] firstLocationLatLng = firstLocationJson.getString("location").split(",");
                            Location firstLocation = new Location(LocationManager.GPS_PROVIDER);
                            firstLocation.setLatitude(Double.parseDouble(firstLocationLatLng[0]));
                            firstLocation.setLongitude(Double.parseDouble(firstLocationLatLng[1]));

                            String[] lastLocationLatLng = lastLocationJson.getString("location").split(",");
                            Location lastLocation = new Location(LocationManager.GPS_PROVIDER);
                            lastLocation.setLatitude(Double.parseDouble(lastLocationLatLng[0]));
                            lastLocation.setLongitude(Double.parseDouble(lastLocationLatLng[1]));

                            final float distance = firstLocation.distanceTo(lastLocation); //distance in meters

                            if (distance > 50000 && distance < 200000) { //distance bigger than 50 km
                                showMapView(response, firstLocation, lastLocation, 7);
                            } else if (distance > 300000) {
                                showMapView(response, firstLocation, lastLocation, 5);
                            }
                        } catch (JSONException e) {
                            // TODO
                        }
                    }
                    // TODO -
                }

Now let's see the method that is drawing our MapView. Note that I am not inside an activity, and if I want to force code to be run on main thread (for updating the UI), I will use a Handler and a Runnable. The method showMapView() is the one taking care of drawing the markers and the locations in between.

    private void showMapView(JSONArray response, Location firstLoc, Location lastLoc, final int zoom) {
    final LatLng latLng1 = new LatLng(firstLoc.getLatitude(), firstLoc.getLongitude());
    final LatLng latLng2 = new LatLng(lastLoc.getLatitude(), lastLoc.getLongitude());
    final MarkerOptions marker1 = new MarkerOptions().position(latLng1);
    final MarkerOptions marker2 = new MarkerOptions().position(latLng2);

    final PolylineOptions polylineOptions = new PolylineOptions();
    final ArrayList<LatLng> points = new ArrayList<LatLng>();
    //saving all the locations in an ArrayList
    if (response.length() > 0) {
        for (int i = 0; i < response.length(); i++) {
            JSONObject locationsJson = null;
            try {
                locationsJson = response.getJSONObject(i);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String locationString = null;
            try {
                locationString = locationsJson.getString("location");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //here I am splitting the location string in a String array. 
            String[] locationLatLng = locationString.split(",");
            Location loc = new Location(LocationManager.GPS_PROVIDER);
            loc.setLatitude(Double.parseDouble(locationLatLng[0]));
            loc.setLongitude(Double.parseDouble(locationLatLng[1]));
            LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude());
            points.add(latLng);

        }
    }

    Handler mainHandler = new Handler(Looper.getMainLooper());

    Runnable myRunnable = new Runnable() {
        @Override
        public void run() {
            mapView.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                    googleMap.addMarker(marker1);
                    googleMap.addMarker(marker2);
                    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng1, zoom));
                    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng2, zoom));
                    polylineOptions.addAll(points);
                    polylineOptions.width(10);
                    polylineOptions.color(Color.BLUE);
                    googleMap.addPolyline(polylineOptions);
                }
            });
        }
    };

    mainHandler.post(myRunnable);
}

The code is plain and clear, the points (intermediate locations) are draw using an object of type PolylineOptions and it is added to the map using this line: googleMap.addPolyline(polylineOptions);

The desired zoom level, is in the range of 2.0 to 21.0. Values below this range are set to 2.0, and values above it are set to 21.0. Increase the value to zoom in. Not all areas have tiles at the largest zoom levels. read here about zoom


I have already given the answer of this question please read the following link blow

Draw line between two points in google map in android

I hope this is help.

0

精彩评论

暂无评论...
验证码 换一张
取 消