如何从Google Directions Api绘制折线

问题描述 投票:1回答:4

我正在尝试从Google Directions Api返回的数据中绘制一个,api有这个字段,overview_polyline,我假设这个字段包含整个折线,所以我在想为什么不从那里绘制折线,这就是什么我有来自谷歌的JSON:

{
     geocoded_waypoints: [
        {},
        {}
     ],
     routes: [
        {
           bounds: {},
           copyrights: "Dados do mapa ©2017 Google, Inst. Geogr. Nacional",
           legs: [],
           overview_polyline: {
               points: "cxwnFtdct@dAQlAf@fAf@|Aq@l@]pCcFhCjA|LfJlAT~@IpDi@jAb@f@HXi@t@kBhBeBx@Qz@z@dClHzFpW`H|RvTpj@`AxAdBdAnAXhB?fBk@rAcAnG_HhCgAjAKrATbA`Al@lBHnAc@rFgBhIkCxMBfIlBvHnBtCnB|AnEdCrJxFj@fB@h@OhAgCtHGfCl@jAlA\jE]tDBzBb@tLxFtK~E`d@hShIzEtDhDxDrEfDpFlFjNvDtRdDjThF`TzH`QhEhG|EvFhL`JpJtE|LpEdOpFjOzGlPfJlHzE~NjLfQvPfP|RtHrKxDjGfI|NdHbOvGjPfCbHpCtIvJh_@vG|[|CtNvFvSvE~MfI|QzLbTfNxQbKlKrRzP|NnNvNlQjIzMnLfV`T|h@nDbHhIdMxFjH~JrMnEfHzIrQfHvOtEjI|MnQfNzP`FzI~EnLrKp[nDlHvErHzL~MbRbM`EjCjFxEtRnX|D~EjIhI~WrRxGlGdFnG`JjNxHzKfTxVfKfRfMbRlErHtBlFxIjYvHnPpBtFxF~WpCjHjGhJfDzClF~CnDlArDl@pC\vHXvX[lOaB|GcBdFqBxQwJbDmAxE_ApJ_@jEXtItBrQ~EbQbDlUfBpMfA|IxCbF`DhGlGnJjKtJrF`SpFbRnDdUxAbGrAlEjBnFpDtNnMfGlE~[lTbRdQjTpUxH`GjHfEnGlC`O|DrUxEnEzAfFrBnSpIjPnDxSlAf\lAl~@hDzRrAjOpBvKrBrQtEv^pM``@rPrR|JxSdMlGnGfGtH~HxFdFlBtGfApGp@bG|AnHxD|FzFrH`L~FvH|HrFrFtBtFjA~Mt@pHR|FhA`IfDpEbDzFxGrHrKhEtErF`EnS`MzMvItSdUfF~DtE~B|SrInEnBzDtCxN`QpQfVtQ~Yjn@~fAnK`RvLlRzEjF|GlFrc@vUfRjKfIvGxDhEjIxKdN~T`L~MrFvE~LhIlp@fb@xCtBzFtFbEzFbDrGhH`TfF|JnGfHzEdD|UdIpTdHtKtFj]nUrEzC~[pTfLfG|EbB~KfCnTvDpmAxSzs@~LhOfDzOdFfOxGdY`O`k@zYnVzMlK|HrFjFbXj[rCbCvDfB|FfBbD^xRBlb@nBrIdArJvDfD|B|FzFvFzHnCbIDrCk@dA_A_@q@mHz@sAvAJ^f@r@n@x@UR_@fBGjET`S~@ro@pCpXpAfFp@dEhCnGtE@HXl@n@H^W|ASpShAbZxAtPp@~SjAzGZKdDStBd@x@dC@nEVz@HtAp@b@\OZ|AbBxDnFJf@"
           },
           summary: "A1",
           warnings: [ ],
           waypoint_order: [ ]
        }
     ],
     status: "OK"
 }

如何使用该值绘制?

android google-maps google-maps-direction-api
4个回答
0
投票

@alb首先你应该解析lat,长期来自JSON。你可以看到这个链接:https://developers.google.com/maps/documentation/directions/

然后你必须获得lat,long值并将它们放在List <>中。

之后,您可以在地图上使用以下代码绘制折线:

PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
    LatLng point = list.get(z);
    options.add(point);
}
line = myMap.addPolyline(options);

0
投票

我已经在下面的链接上回答了类似的问题

How to buffer a polyline in Android or draw a polygon around a polyline?

它可能会解决您的问题


0
投票

这对我有帮助,你可以使用它..首先从谷歌开发者帐户创建一个谷歌服务器密钥

GoogleDirection.withServerKey(getResources().getString(R.string.SERVER_KEY))
                        .from(SourceLatlng)
                        .to(DestinationLatlng)
                        .execute(new DirectionCallback() {
                            @Override
                            public void onDirectionSuccess(Direction direction, String message) {
                                if (direction.isOK()) {
                                    routeSucess2(direction, message,SourceLatlng,DestinationLatlng);
                                } else {
                                    //selectedRawLine = ERROR;
                                }

                            }

                            @Override
                            public void onDirectionFailure(Throwable t) {
                                t.printStackTrace();
                            }
                        });

然后使用谷歌方向画一条路线

 private void routeSucess2(Direction direction, String message,LatLng sourceLatlng,LatLng DestinationLng) {

        for (Route route : direction.getRouteList()) {
            PolylineOptions polyoptions = new PolylineOptions();
            polyoptions.color(getResources().getColor(R.color.primary__dark));
            polyoptions.width(5);
            polyoptions.addAll(route.getOverviewPolyline().getPointList());
            poly = googleMap.addPolyline(polyoptions);
            poly.setClickable(true);

        }
        LatLngBounds.Builder latLngBuilder = new LatLngBounds.Builder();
        if(sourceLatlng!=null)
        latLngBuilder.include(sourceLatlng);
        if(DestinationLng!=null)
        latLngBuilder.include(DestinationLng);

        try {
            LatLngBounds bounds = latLngBuilder.build();
            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
                    UiHelper.dpToPixel(getActivity(), 135));
            googleMap.animateCamera(cu);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

这会对你有所帮助。


0
投票

不要使用overview_path作为折线,它不包括所有点,从所有腿中抓取点并使用它们来创建折线。

var polyline = new google.maps.Polyline({
  path: [],
  strokeColor: '#FF0000',
  strokeWeight: 3
});
var bounds = new google.maps.LatLngBounds();


var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
  var steps = legs[i].steps;
  for (j=0;j<steps.length;j++) {
    var nextSegment = steps[j].path;
    for (k=0;k<nextSegment.length;k++) {
      polyline.getPath().push(nextSegment[k]);
      bounds.extend(nextSegment[k]);
    }
  }
}

polyline.setMap(map);
map.fitBounds(bounds);

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(51.276092, 1.028938),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer({
    map: map,
    preserveViewport: true
  });
  directionsService.route({
    origin: new google.maps.LatLng(51.269776, 1.061326),
    destination: new google.maps.LatLng(51.30118, 0.926486),
    waypoints: [{
      stopover: false,
      location: new google.maps.LatLng(51.263439, 1.03489)
    }],
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      // directionsDisplay.setDirections(response);
      var polyline = new google.maps.Polyline({
        path: [],
        strokeColor: '#0000FF',
        strokeWeight: 3
      });
      var bounds = new google.maps.LatLngBounds();


      var legs = response.routes[0].legs;
      for (i = 0; i < legs.length; i++) {
        var steps = legs[i].steps;
        for (j = 0; j < steps.length; j++) {
          var nextSegment = steps[j].path;
          for (k = 0; k < nextSegment.length; k++) {
            polyline.getPath().push(nextSegment[k]);
            bounds.extend(nextSegment[k]);
          }
        }
      }

      polyline.setMap(map);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
© www.soinside.com 2019 - 2024. All rights reserved.