【问题标题】:Google map cluster with direction带方向的谷歌地图集群
【发布时间】:2014-07-09 06:36:44
【问题描述】:

我们有一个Google map library 来显示集群中的多个标记。

我有两个问题:

1. 我们可以像下图那样在谷歌地图上显示多个方向吗?

2. 我们可以在簇标记中显示多个方向细节吗?

集群如下:

我会给你例子:来自印度的国家我在我的数据库中保存了不同的方向。

喜欢

艾哈迈达巴德到德里

德里到阿格拉

艾哈迈达巴德到孟买

斋浦尔到德里

我必须根据缩放级别显示上述方向的集群, 当用户缩放谷歌地图时,谷歌地图上会显示多个方向,而不是集群。

我想知道它是否可能?如果是那怎么办?

【问题讨论】:

  • 是否要将多个方向显示为一个集群??
  • 你有方向路径两点的纬度和经度吗?即(从,到)。
  • 那么,我理解正确吗? 1)您希望在地图上显示多条方向线 2)如果方向线在一定的容差范围内,则不会渲染它们,而是显示一个集群标记 3)如果单击/悬停集群标记然后.. . 你想显示方向吗?另外,您是如何检索方向信息的?是通过谷歌方向 API 还是其他来源?
  • @GHC:请再次检查问题...

标签: android google-maps


【解决方案1】:

您可以使用 Directions API 来实现您的目标。您提供起点和终点(可以是纬度/经度或地点名称)。另一个必填字段是出行方式(默认驾驶)。

现在方向返回可以转换为折线然后在地图上绘制的顶点。 This answer 做得很好,我将使用它的代码。

package com.example.simon.maps;

import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Document;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.util.SparseArray;

/**
 * Created by Simon on 2014 Jul 25.
 */

public class MainActivity extends FragmentActivity {

    final static String TAG = "MainActivity";
    GoogleMap mMap;
    GMapV2Direction md;
    int mZoomLevel;
    final float STARTING_ZOOM = 5.0f;
    // List of polylines for each zoom level
    SparseArray<List<Polyline>> mPolylines = new SparseArray<List<Polyline>>();

    public class direction {
        String start, end;
        int zoomLevel;

        direction(String pStart, String pEnd, int pZoomLevel) {
            start = pStart;
            end = pEnd;
            zoomLevel = pZoomLevel;
        }
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy p = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(p);
        }

        md = new GMapV2Direction();
        mMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();

        List<direction> directions = new ArrayList<direction>();
        directions.add(new direction("Ahmedabad,Gujarat,India", "delhi,India", 4));
        directions.add(new direction("Ahmedabad,Gujarat,India","Bombay,Maharashtra,India", 4));
        directions.add(new direction("Jeypore,Odisha,India", "delhi,India", 5));
        for (MainActivity.direction direction : directions) {
            // Query
            Document doc = md.getDocument(direction.start, direction.end);
            // Parse the xml
            if (doc == null) {
                Log.e(TAG, "Failed to get the route from " + direction.start
                        + " to " + direction.end);
                continue;
            }
            // Get points
            ArrayList<LatLng> directionPoint = md.getDirection(doc);
            // Convert vertexes to a polyline
            PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
            for (LatLng aDirectionPoint : directionPoint) {
                rectLine.add(aDirectionPoint);
            }
            // Add poly to the map
            addPolyline(rectLine, direction.zoomLevel);
        }
        // Get the starting point of the first direction
        LatLng start = mPolylines.valueAt(0).get(0).getPoints().get(0);
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(start, STARTING_ZOOM), 1000, null);
        // Set the initial zoom level and show the necessary polylines
        mZoomLevel = (int) STARTING_ZOOM;
        initPolylines(mZoomLevel);

        // Listen for the camera zoom level changes
        mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                // Note that because we are casting the zoomLevel to int,
                // it will be considered as changed only when it reaches
                // a new integer when rounded (e.g. 5.0, 6.0 etc.)
                int newZoomLevel = (int) cameraPosition.zoom;
                if (newZoomLevel != mZoomLevel) {
                    Log.d(TAG, "New zoom level: " + newZoomLevel);
                    // Loop all the changed zoom levels
                    // E.g. zoomed-out from 15 to 13, then hide [14, 15]
                    if (newZoomLevel < mZoomLevel) { // Zoomed out
                        for (int i=1; i<=mZoomLevel-newZoomLevel; i++)
                            hidePolylines(mPolylines.get(newZoomLevel+i));
                    } else { // Zoomed-in
                        for (int i=1; i<=newZoomLevel-mZoomLevel; i++)
                            showPolylines(mPolylines.get(mZoomLevel + i));
                    }
                    mZoomLevel = newZoomLevel;
                }
            }
        });
    }

    private void addPolyline(PolylineOptions polyOpts, int zoomLevel) {
        List<Polyline> polylines = mPolylines.get(zoomLevel);
        // Create polyline list for this zoom level, if it still doesn't exist
        if (polylines == null) {
            polylines = new ArrayList<Polyline>();
            mPolylines.put(zoomLevel, polylines);
        }
        // Append a new item to this poly list
        Polyline polyline = mMap.addPolyline(polyOpts);
        polyline.setVisible(false);
        polylines.add(polyline);
    }

    private void initPolylines(int zoomLevel) {
        for(int i=0; i<mPolylines.size(); i++) {
            // Loop until zoom level is reached
            if  (mPolylines.keyAt(i) > zoomLevel) break;

            showPolylines(mPolylines.get(mPolylines.keyAt(i)));
        }
    }

    private void showPolylines(List<Polyline> polylines) {
        if (polylines != null)
            for (Polyline polyline : polylines) polyline.setVisible(true);
    }

    private void hidePolylines(List<Polyline> polylines) {
        if (polylines != null)
            for (Polyline polyline : polylines) polyline.setVisible(false);
    }

}

此代码将折线添加到 SparseArray 中,该数组保存每个缩放级别的折线。默认情况下,所有策略都是隐藏的,只有在达到特定缩放级别时才会显示(也在initPolylines)。

这里有几点需要注意:

  1. 因为缩放可以一次改变几个级别,我们循环每个级别来隐藏/显示特定的方向。
  2. 位置名称必须准确,否则将找不到它们,并且您可能会在代码中收到一堆错误(我只添加了一个 Log.e)
  3. 如果要创建标记,比如说方向的起点和终点,可以使用以下代码获取坐标:

    List<LatLng> points = mPolylines.valueAt(0).get(0).getPoints();
    LatLng start = points.get(0);
    LatLng end = points.get(points.size()-1);
    
  4. 可以在特定缩放级别添加/删除标记,就像在此处使用折线完成的一样。

这里是 xml 解析器 (GMapV2Direction) 的代码:

package com.example.simon.maps;

import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.google.android.gms.maps.model.LatLng;

public class GMapV2Direction {

    public GMapV2Direction() { }

    public Document getDocument(String start, String end) {
        String url = "http://maps.googleapis.com/maps/api/directions/xml?"
                + "origin="+start+"&destination="+end+"&units=metric&mode=driving";
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse response = httpClient.execute(httpPost, localContext);
            InputStream in = response.getEntity().getContent();
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            return builder.parse(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public ArrayList<LatLng> getDirection (Document doc) {
        NodeList nl1, nl2, nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");
        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));

                locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "points"));
                ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
                for (LatLng anArr : arr) {
                    listGeopoints.add(new LatLng(anArr.latitude, anArr.longitude));
                }

                locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "lat"));
                lat = Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    private int getNodeIndex(NodeList nl, String nodename) {
        for(int i = 0 ; i < nl.getLength() ; i++) {
            if(nl.item(i).getNodeName().equals(nodename))
                return i;
        }
        return -1;
    }

    private ArrayList<LatLng> decodePoly(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 position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
            poly.add(position);
        }
        return poly;
    }
}

一些最后的笔记:

  • 如果您有很多方向,请将它们加载到 initPolylinesshowPolylines 中并在 hidePolylines 中卸载它们
  • 如果您要在地图上显示的方向不变,最好的方法是在特定缩放级别上使用带有折线的图块。 Maperitive 是一个很好的免费工具,它可以将图块导出到任意数量的缩放级别。然后,您将在线存储图块并使用 UrlTileProvider 将它们显示在您的地图上。

【讨论】:

    【解决方案2】:

    我不知道我是否正确理解了您的问题,但无论如何我都会尝试回答。 您可以创建多个 polylines 并从来自 google maps direction API 的 JSON 响应添加到映射。这样您就可以在一张地图中添加多条路线。

    据我了解第二个问题,您希望集群标记提供您正在绘制的路线的详细信息。为此,我想您可以对 API 返回的点进行聚类并使用custom marker clusters 来显示您想要的信息。

    希望对你有帮助

    -编辑- 如果您想在 Android 应用程序中绘制路线,您没有任何可以使用的 DirectionRenderer。您需要使用折线渲染路线。这就是我在上面的答案中提到创建折线的原因。作为对 Direction 请求的响应,您将获得一个包含多个坐标点的 JSON,这些坐标点可以通过在它们之间绘制折线来连接。 您可以在地图上拥有多条这样的折线(从任意点到任意点)。 案例 1:您想要 2 条从孟买到果阿的路线,将替代参数设置为 true。 案例 2:您想要两条不同的路线,班加罗尔到孟买,果阿到德里,向 API 发出两个不同的请求。您将获得两条不同的路线并在地图上绘制它们。

    对于您的第二个问题,由于路线(折线)没有内置集群,您必须对地图中显示的集群图标的逻辑进行编码。要获取当前缩放级别,请使用以下命令。

    GoogleMap map;    
    float zoom = map.getCameraPosition().zoom;
    

    用于显示和隐藏折线

    Polyline line = map.addPolyline(new PolylineOptions()
     .add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
    
     // multiple points that you get from the response of directions API
    
     .width(5)
     .color(Color.RED));
    
    //your logic for visibility
    if(zoom<=5){
      line.setVisible(true);
    }
    

    我在 API 中找不到使用代码隐藏集群图标的任何方法。我想它应该在一定的缩放级别后隐藏起来。

    【讨论】:

    • 不想要多条polilines,寻找从一个地方到另一个地方的多个方向
    • 如果您检查路线 API 的链接,它有一个选项 'alternatives' 如果设置为 true,将提供从一个点到另一个点的多条路线。
    • 您查看了附件图片吗?有多少个方向?
    • 在附图中,您展示了 3 条不同的路线,原始解决方案应该适用于这些路线(为您拥有的多条路线创建折线)(您可以通过查询 google 方向来获取路线的点API)。在 cmets 中,您说您想要“从一个地方到另一个地方的多个方向”,这就是我回答该解决方案的原因。如果这不是您想要的,您应该为问题添加更好的描述。
    猜你喜欢
    • 2017-06-13
    • 2021-11-10
    • 2019-01-20
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多