绘制 2 个叠加层之间的路线

发布于 2024-11-14 19:35:00 字数 5064 浏览 3 评论 0原文

在我的应用程序中,我在地图上显示了 2 个位置,并用标记标记了它们。现在,我想画出它们之间的路线,但我不知道该怎么做。我的函数绘制应该是什么样子?

这是我的代码:

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());
        }
    }
}

谢谢..

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..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

再浓的妆也掩不了殇 2024-11-21 19:35:00

因此,假设您正在从 REST Web 服务获取位置(以 JSON 格式)。为此,我使用 Volley 库来连接并获取服务器的响应。

JSONArray 响应示例:

[ {...,"位置":"44.924654,8.586219", ...},
{...,"位置":"44.906177,8.157752", ...},
{...,“位置”:“44.906177,8.157752”,...},{...,“位置”:
"44.956733,7.876227", ...}, {...,"位置": "45.034424,7.671607",
...}]

该步骤是将第一个和最后一个位置设置为标记,中间位置将在它们之间绘制线。

因为位置是作为字符串获取的,所以我们首先要分割字符串,并将“,”之前的部分分配给纬度,其余部分分配给经度。

                    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 -
                }

现在让我们看看绘制 MapView 的方法。请注意,我不在活动内,如果我想强制代码在主线程上运行(用于更新 UI),我将使用 Handler 和 Runnable。
showMapView() 方法负责绘制标记及其之间的位置。

    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);
}

代码简单明了,点(中间位置)是使用 PolylineOptions 类型的对象绘制的,并使用以下行将其添加到地图中: googleMap.addPolyline(polylineOptions);

所需的缩放级别,范围为 2.0 至 21.0。低于此范围的值设置为 2.0,高于此范围的值设置为 21.0。增加值以放大。并非所有区域都具有最大缩放级别的图块。
在此处阅读有关缩放的信息

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

凉薄对峙 2024-11-21 19:35:00

我已经给出了这个问题的答案,请阅读以下链接

在 android 中的谷歌地图中的两点之间绘制线

我希望这有帮助。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文