在 Javascript 中获取 google 地图编码多段线的开始和结束坐标

Get start and end coordinates of a google maps encoded polyline in Javascript

我想获取 google encoded polyline string 的开始和结束 lat/longs:

_p~iF~ps|U_ulLnnqC_mqNvxq`@

给我这样的东西:

[38.5,-120.2],[43.252,-126.453] //lat,lng of start and end

我应该如何在 Javascript 中完成它?

最简单的方法是使用 Google 地图 Javascript API google.maps.geometry.encoding.decodePath 方法。

proof of concept fiddle

代码片段:

var encodedStr = "_p~iF~ps|U_ulLnnqC_mqNvxq`@";

function initialize() {
  var mapOptions = {
    zoom: 14,
    center: new google.maps.LatLng(34.3664951, -89.5192484)
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);
  var path = google.maps.geometry.encoding.decodePath(encodedStr);
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < path.length; i++) {
    if (i==0) document.getElementById('startpoint').value = path[i].toUrlValue(6);
    if (i==path.length-1) document.getElementById('endpoint').value = path[i].toUrlValue(6);
    bounds.extend(path[i]);
  }
  map.fitBounds(bounds);
  var polyOptions = {
    strokeColor: '#000000',
    strokeOpacity: 1.0,
    strokeWeight: 3,
    map: map,
    path: path
  };
  poly = new google.maps.Polyline(polyOptions);
}

google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<label>start</label>&nbsp;<input type="text" id="startpoint"/><br>
<label>end</label>&nbsp;<input type="text" id="endpoint" />
<div id="map-canvas" style="border: 2px solid #3872ac;"></div>

如果你想要一个独立的 javascript 函数,使用这个:

//check the precision
var decompressed = decompress(encoded, 6);

function decompress (encoded, precision) {
    precision = Math.pow(10, -precision);
    var len = encoded.length, index=0, lat=0, lng = 0, array = [];
    while (index < len) {
        var b, shift = 0, result = 0;
        do {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lng += dlng;
        array.push(lat * precision);
        array.push(lng * precision);
    }
    return array;
}