Google Maps Encode Polyline Rendering Wrong

▼魔方 西西 提交于 2019-12-25 12:42:35

问题


I am having problems rendering polylines on a Google map for my univer. The result should look like the polyline on: http://goo.gl/U18jBJ (Google maps directions from Leeds to London).

I am rendering individual paths from each step from the Google directions API instead of just getting a Google directions map, so that I can use a loop to render the individual paths from each step from the Google directions API and the polyline paths in the Rome2Rio Search API result.

The following php writes out the javascript for the map:

<script type="text/javascript">
function initialize() {
var myLatLng = new google.maps.LatLng(53.796490000000006, -1.5473400000000002);
var myOptions = {
    zoom: 8,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("routeMap"), myOptions);

<?php $stopCounter = 0;
foreach($travelData[0]->stops as $stop):
    echo 'var stopLatlng'.$stopCounter.' = new google.maps.LatLng('.$stop->location.');';
    echo 'var marker'.$stopCounter.' = new google.maps.Marker({
              position: stopLatlng'.$stopCounter.',
              map: map,
              title: \''.$stop->name.'\'
          });';
    ++$stopCounter;
endforeach; 
$segementCounter = 0;
foreach($travelData[0]->segments as $segment):
    echo 'var routePath'.$segementCounter.' = \''.$segment->path.'\'; ';
    echo 'var path'.$segementCounter.' = google.maps.geometry.encoding.decodePath(String(routePath'.$segementCounter.')); ';
    echo 'var route'.$segementCounter.' = new google.maps.Polyline({
              path: path'.$segementCounter.',
              strokeColor: "#FF0000",
              strokeOpacity: 1.0,
              strokeWeight: 2
            }); ';
    ++$segementCounter;
endforeach;
$segementCounter = 0;
foreach($travelData[0]->segments as $segment):
    echo 'route'.$segementCounter.'.setMap(map);';
    ++$segementCounter;
endforeach;?>

}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="routeMap" class="floatLeft">
</div>

From my research, it seems that it is the javascript which is causing problems (possibly by escaping characters) but I cannot find a resolution. The code output by the php is here: http://jsfiddle.net/phily245/ebbCX/


回答1:


The backslashes in the encoded path must be escaped with another backslash:

http://jsfiddle.net/doktormolle/ebbCX/2/

using json_encode should preserve the original string(assuming that the backslashes have been escaped in the original string):

echo 'var routePath'.$segementCounter.' = '.json_encode($segment->path).';';


来源:https://stackoverflow.com/questions/22309961/google-maps-encode-polyline-rendering-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!