在Javascript中获取谷歌地图编码折线的起点和终点坐标

时间:2015-07-02 09:53:54

标签: javascript google-maps gis polyline

我想获得google encoded polyline string的开头和结尾:

_p~iF~ps|U_ulLnnqC_mqNvxq`@

给我一​​些类似的东西:

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

我应该如何在Javascript中执行此操作?

2 个答案:

答案 0 :(得分:2)

最简单的方法是使用Google Maps 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);
&#13;
html,
body,
#map-canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

如果你想要一个独立的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;
}