Google 地图路线 - 哪个 API?

2023-12-06

我正在尝试获取从用户当前位置到我正在构建的应用程序中用户定义位置的路线。这看起来应该是一件相对容易的事情,但我在使用哪个 API 上遇到了困难。

现在我已经成功连接到谷歌路线API但它返回的 JSON 非常奇怪(他们在各处添加了 \n 以使其易于阅读),这表明这个 API 不适合移动设备。

我还看到 google place API 被推荐用于此目的,但我似乎无法从文档中找到如何使用它。

非常感谢任何帮助,因为我只是有点困惑

编辑:为了澄清问题,我应该使用哪个 API 来获取地图方向?


我不记得从哪里得到的,但这个课程对我帮助很大,它包括你是否想画路线。

谷歌解析器.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.monumentos.log.Logger;

public class GoogleParser extends XMLParser implements Parser {
    /** Distance covered. **/
    private int distance;

    public GoogleParser(String feedUrl) {
            super(feedUrl);
    }

    /**
     * Parses a url pointing to a Google JSON object to a Route object.
     * @return a Route object based on the JSON object.
     */

    public Route parse() {
            // turn the stream into a string
            final String result = convertStreamToString(this.getInputStream());
            //Create an empty route
            final Route route = new Route();
            //Create an empty segment
            final Segment segment = new Segment();
            try {
                    //Tranform the string into a json object
                    final JSONObject json = new JSONObject(result);
                    //Get the route object
                    final JSONObject jsonRoute = json.getJSONArray("routes").getJSONObject(0);
                    //Get the leg, only one leg as we don't support waypoints
                    final JSONObject leg = jsonRoute.getJSONArray("legs").getJSONObject(0);
                    //Get the steps for this leg
                    final JSONArray steps = leg.getJSONArray("steps");
                    //Number of steps for use in for loop
                    final int numSteps = steps.length();
                    //Set the name of this route using the start & end addresses
                    route.setName(leg.getString("start_address") + " to " + leg.getString("end_address"));
                    //Get google's copyright notice (tos requirement)
                    route.setCopyright(jsonRoute.getString("copyrights"));
                    //Get the total length of the route.
                    route.setLength(leg.getJSONObject("distance").getInt("value"));
                    //Get any warnings provided (tos requirement)
                    if (!jsonRoute.getJSONArray("warnings").isNull(0)) {
                            route.setWarning(jsonRoute.getJSONArray("warnings").getString(0));
                    }
                    /* Loop through the steps, creating a segment for each one and
                     * decoding any polylines found as we go to add to the route object's
                     * map array. Using an explicit for loop because it is faster!
                     */
                    for (int i = 0; i < numSteps; i++) {
                            //Get the individual step
                            final JSONObject step = steps.getJSONObject(i);
                            //Get the start position for this step and set it on the segment
                            final JSONObject start = step.getJSONObject("start_location");
                            final GeoPoint position = new GeoPoint((int) (start.getDouble("lat")*1E6), 
                                    (int) (start.getDouble("lng")*1E6));
                            segment.setPoint(position);
                            //Set the length of this segment in metres
                            final int length = step.getJSONObject("distance").getInt("value");
                            distance += length;
                            segment.setLength(length);
                            segment.setDistance(distance/1000);
                            //Strip html from google directions and set as turn instruction
                            segment.setInstruction(step.getString("html_instructions").replaceAll("<(.*?)*>", ""));
                            //Retrieve & decode this segment's polyline and add it to the route.
                            route.addPoints(decodePolyLine(step.getJSONObject("polyline").getString("points")));
                            //Push a copy of the segment to the route
                            route.addSegment(segment.copy());
                    }
            } catch (JSONException e) {

                    Logger.appendLog( "Google JSON Parser - " + feedUrl);
            }
            return route;
    }

    /**
     * Convert an inputstream to a string.
     * @param input inputstream to convert.
     * @return a String of the inputstream.
     */

    private static String convertStreamToString(final InputStream input) {
    final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    final StringBuilder sBuf = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sBuf.append(line);
        }
    } catch (IOException e) {
            Logger.appendLog( "Google parser, stream2string");
    } finally {
        try {
            input.close();
        } catch (IOException e) {
            Logger.appendLog( "Google parser, stream2string");
        }
    }
    return sBuf.toString();
}

    /**
     * Decode a polyline string into a list of GeoPoints.
     * @param poly polyline encoded string to decode.
     * @return the list of GeoPoints represented by this polystring.
     */

    private List<GeoPoint> decodePolyLine(final String poly) {
            int len = poly.length();
            int index = 0;
            List<GeoPoint> decoded = new ArrayList<GeoPoint>();
            int lat = 0;
            int lng = 0;

            while (index < len) {
            int b;
            int shift = 0;
            int result = 0;
            do {
                    b = poly.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 = poly.charAt(index++) - 63;
                    result |= (b & 0x1f) << shift;
                    shift += 5;
            } while (b >= 0x20);
                    int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
                    lng += dlng;

            decoded.add(new GeoPoint(
                    (int) (lat*1E6 / 1E5), (int) (lng*1E6 / 1E5)));
            }

            return decoded;
            }
}

解析器.java

public interface Parser {
    public Route parse();
}

路线.java

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

import com.google.android.maps.GeoPoint;

public class Route {
    private String name;
    private final List<GeoPoint> points;
    private List<Segment> segments;
    private String copyright;
    private String warning;
    private String country;
    private int length;
    private String polyline;

    public Route() {
            points = new ArrayList<GeoPoint>();
            segments = new ArrayList<Segment>();
    }

    public void addPoint(final GeoPoint p) {
            points.add(p);
    }

    public void addPoints(final List<GeoPoint> points) {
            this.points.addAll(points);
    }

    public List<GeoPoint> getPoints() {
            return points;
    }

    public void addSegment(final Segment s) {
            segments.add(s);
    }

    public List<Segment> getSegments() {
            return segments;
    }

    /**
     * @param name the name to set
     */
    public void setName(final String name) {
            this.name = name;
    }

    /**
     * @return the name
     */
    public String getName() {
            return name;
    }

    /**
     * @param copyright the copyright to set
     */
    public void setCopyright(String copyright) {
            this.copyright = copyright;
    }

    /**
     * @return the copyright
     */
    public String getCopyright() {
            return copyright;
    }

    /**
     * @param warning the warning to set
     */
    public void setWarning(String warning) {
            this.warning = warning;
    }

    /**
     * @return the warning
     */
    public String getWarning() {
            return warning;
    }

    /**
     * @param country the country to set
     */
    public void setCountry(String country) {
            this.country = country;
    }

    /**
     * @return the country
     */
    public String getCountry() {
            return country;
    }

    /**
     * @param length the length to set
     */
    public void setLength(int length) {
            this.length = length;
    }

    /**
     * @return the length
     */
    public int getLength() {
            return length;
    }


    /**
     * @param polyline the polyline to set
     */
    public void setPolyline(String polyline) {
            this.polyline = polyline;
    }

    /**
     * @return the polyline
     */
    public String getPolyline() {
            return polyline;
    }

}



RouteOverlay.java

public class RouteOverlay extends Overlay {
/** GeoPoints representing this routePoints. **/
private final List<GeoPoint> routePoints;
/** Colour to paint routePoints. **/
private int colour;
/** Alpha setting for route overlay. **/
private static final int ALPHA = 200;
/** Stroke width. **/
private static final float STROKE = 4.5f;
/** Route path. **/
private final Path path;
/** Point to draw with. **/
private final Point p;
/** Paint for path. **/
private final Paint paint;


/**
 * Public constructor.
 * 
 * @param route Route object representing the route.
 * @param defaultColour default colour to draw route in.
 */

public RouteOverlay(final Route route, final int defaultColour) {
        super();
        routePoints = route.getPoints();
        colour = defaultColour;
        path = new Path();
        p = new Point();
        paint = new Paint();
}

@Override
public final void draw(final Canvas c, final MapView mv,
                final boolean shadow) {
        super.draw(c, mv, shadow);

        paint.setColor(colour);
        paint.setAlpha(ALPHA);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(STROKE);
        paint.setStyle(Paint.Style.STROKE);

        redrawPath(mv);
        c.drawPath(path, paint);
}

/**
 * Set the colour to draw this route's overlay with.
 * 
 * @param c  Int representing colour.
 */
public final void setColour(final int c) {
        colour = c;
}

/**
 * Clear the route overlay.
 */
public final void clear() {
        routePoints.clear();
}

/**
 * Recalculate the path accounting for changes to
 * the projection and routePoints.
 * @param mv MapView the path is drawn to.
 */

private void redrawPath(final MapView mv) {
        final Projection prj = mv.getProjection();
        path.rewind();
        final Iterator<GeoPoint> it = routePoints.iterator();
        prj.toPixels(it.next(), p);
        path.moveTo(p.x, p.y);
        while (it.hasNext()) {
                prj.toPixels(it.next(), p);
                path.lineTo(p.x, p.y);
        }
        path.setLastPoint(p.x, p.y);
}

}

段.java

    import com.google.android.maps.GeoPoint;

public class Segment {
    /** Points in this segment. **/
    private GeoPoint start;
    /** Turn instruction to reach next segment. **/
    private String instruction;
    /** Length of segment. **/
    private int length;
    /** Distance covered. **/
    private double distance;

    /**
     * Create an empty segment.
     */

    public Segment() {
    }


    /**
     * Set the turn instruction.
     * @param turn Turn instruction string.
     */

    public void setInstruction(final String turn) {
            this.instruction = turn;
    }

    /**
     * Get the turn instruction to reach next segment.
     * @return a String of the turn instruction.
     */

    public String getInstruction() {
            return instruction;
    }

    /**
     * Add a point to this segment.
     * @param point GeoPoint to add.
     */

    public void setPoint(final GeoPoint point) {
            start = point;
    }

    /** Get the starting point of this 
     * segment.
     * @return a GeoPoint
     */

    public GeoPoint startPoint() {
            return start;
    }

    /** Creates a segment which is a copy of this one.
     * @return a Segment that is a copy of this one.
     */

    public Segment copy() {
            final Segment copy = new Segment();
            copy.start = start;
            copy.instruction = instruction;
            copy.length = length;
            copy.distance = distance;
            return copy;
    }

    /**
     * @param length the length to set
     */
    public void setLength(final int length) {
            this.length = length;
    }

    /**
     * @return the length
     */
    public int getLength() {
            return length;
    }

    /**
     * @param distance the distance to set
     */
    public void setDistance(double distance) {
            this.distance = distance;
    }

    /**
     * @return the distance
     */
    public double getDistance() {
            return distance;
    }

}

XMLParser.java

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import com.monumentos.log.Logger;

public class XMLParser {
    // names of the XML tags
    protected static final String MARKERS = "markers";
    protected static final String MARKER = "marker";

    protected URL feedUrl;

    protected XMLParser(final String feedUrl) {
            try {
                    this.feedUrl = new URL(feedUrl);
            } catch (MalformedURLException e) {
                Logger.appendLog( "XML parser - " + feedUrl);
            }
    }

    protected InputStream getInputStream() {
            try {
                    return feedUrl.openConnection().getInputStream();
            } catch (IOException e) {
                Logger.appendLog(  "XML parser - " + feedUrl);
                    return null;
            }
    }
}

希望它会对您有所帮助。

调用api示例:

        Parser parser;

        String jsonURL = "http://maps.googleapis.com/maps/api/directions/json?";
        final StringBuffer sBuf = new StringBuffer(jsonURL);
        sBuf.append("origin=");
        sBuf.append( points.get(0).getLatitudeE6()/1E6);
        sBuf.append(',');
        sBuf.append(points.get(0).getLongitudeE6()/1E6);
        sBuf.append("&destination=");
        sBuf.append(points.get(points.size()-1).getLatitudeE6()/1E6);
        sBuf.append(',');
        sBuf.append(points.get(points.size()-1).getLongitudeE6()/1E6);

        sBuf.append("&sensor=true&mode="+routeMode);


        Logger.appendLog(sBuf.toString());


        parser = new GoogleParser(sBuf.toString());

        Route r =  parser.parse();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Google 地图路线 - 哪个 API? 的相关文章

随机推荐

  • 在 Python 中解析 Twitter JSON 对象

    我正在尝试从 Twitter 下载推文 我为此使用了 python 和 Tweepy 虽然我对 Python 和 Twitter API 都很陌生 我的Python脚本如下 usr bin python import modules imp
  • 根据 PWD 更新多项缓冲区名称

    如果我使用 konsole 或其他终端 终端标签名称可以根据 PWD 更改 但在多项中 缓冲区名称是 terminal
  • 如何在 WPF 中创建反斜杠键的键绑定?

    Trying to define a CTRL Backslash keybinding for our WPF command but we re running into two issues 反斜杠键没有任何预定义常量 只有 Oem
  • 如何向下滚动 UITable 视图,直到在 Calabash 中看到带有标签“Value”的单元格

    如何向下滚动 UITableView 直到看到带有标签 Value 的单元格葫芦 黄瓜 我一直在尝试使用以下方法来做到这一点 Then I swipe down until I see Value 并使用 Then I scroll dow
  • 有没有办法在属性网格之外使用 CollectionEditor?

    我正在用一些可以让我更好地自定义 UI 的东西替换我的属性网格 我在表单上放置了一个按钮 我希望单击该按钮时会弹出一个 CollectionEditor 并允许我修改我的代码 当我使用 PropertyGrid 时 我所需要做的就是向指向我
  • 使用 Flexbox 在具有共享标题的两列布局中拉伸列

    我正在使用 Flexbox 创建带有标题行的两列布局 box sizing border box position relative container border 2px solid gray display flex flex wra
  • VBA - 将 SAPI 语音保存到给定的文件类型?

    My Task 可以在 Office 应用程序中使用语音 我的目标是将 MS SAPI 语音保存为给定的文件类型 AFAIK 我的代码示例保存到 WAV 文件 Problem 我不知道是否可以仅定义所需的文件类型扩展名 或者是否有必要进行一
  • 来自 Qt C++ 应用程序的倍频程图

    我有一个 QT C 应用程序 它使用 QProcess 运行 Octave 程序 我可以通过读取标准输出 错误并使用 write 方法写入其标准输入 例如 octave gt write 5 5 n 来与它进行通信 正如我告诉你的 我得到了
  • 屏幕方向更改时旋转视图(但不是布局)

    我想旋转按钮 文本视图 等 屏幕方向发生变化 但我想保持布局不变 如何做呢 我正在使用线性布局 This is what I mean Create res gt layout gt layout land并将你的 xml 文件放入横向 模
  • 要避免的 jQuery 陷阱 [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心以获得指导 我正在用 jQuery 启
  • dblookupcombobox 有空行

    我有一个关于 DBLookupComboBox 的问题 我有一个程序 其中有我编写的数据库 它拥有一切 除了当我打开 DBLookupComboBox 时 它必须有一行带有空值 因为当用户不想选择任何内容时 但没有一个 如何让空行显示出来
  • Kotlin 中是否有适用于可序列化类型的接口?

    我想创建一个大致如下所示的类 class MyWrapperClass
  • 如何控制推送通知中按钮的功能?

    我能够向 iOS 设备发送推送通知 通知上有一个 关闭 按钮和一个 查看 按钮 当用户点击 查看 按钮时 应用程序将打开根视图控制器 该应用程序内有一个新闻部分 假设该通知是为了提醒用户有新的新闻报道可供他们查看 如果他们点击 查看 将显示
  • 每当 Android 派中的应用程序被杀死时,服务也会被杀死

    我正在通过创建 Android 应用程序来学习 Android 编程 但是每当我杀死应用程序服务时也会被杀死 我在用着JobIntentService 使该应用程序在后台运行 工作意图服务类 public class BackGroundD
  • Windows 服务中的 TCP IP 侦听器

    我正在尝试创建一个需要在后台运行并侦听传入流量的 Windows 服务 正常且常规的 TCP 侦听器 我的代码是 private TcpListener server public void startServer EventLog Wri
  • 如何使 razor 成为现有项目中的默认视图引擎

    我将 MVC 2 项目升级到 MVC 3 如何在现有项目上将默认视图引擎设置为 Razor 编辑 抱歉 我不太清楚 我希望 Razor 成为 添加视图 对话框中的默认类型 简短回答 更改 global asax 以同时使用 Webforms
  • 通讯Arduino-C++不读Arduino

    我有以下代码 QSerialPort arduPort COM5 arduPort setBaudRate QSerialPort Baud9600 arduPort setDataBits QSerialPort Data8 arduPo
  • Push_back() 导致程序在进入 main() 之前停止

    我正在为我的 STM32F3 Discovery 板使用 C 进行开发 并使用 std deque 作为队列 在尝试调试我的代码 直接在带有 ST link 的设备上或在模拟器中 后 代码最终在 main 中输入我的代码之前在断点处停止 然
  • 为什么在 Angular 中使用 $http 而不是 jquery 的 ajax?

    我不明白何时使用 Angular 而不是 jquery 来处理 ajax 请求 例如 我为什么要使用 function ItemListCtrl scope http http get example com items success f
  • Google 地图路线 - 哪个 API?

    我正在尝试获取从用户当前位置到我正在构建的应用程序中用户定义位置的路线 这看起来应该是一件相对容易的事情 但我在使用哪个 API 上遇到了困难 现在我已经成功连接到谷歌路线API但它返回的 JSON 非常奇怪 他们在各处添加了 n 以使其易