用户在2个文本输入中插入出发和目的地城市,然后单击按钮以在与插入的城市对应的Google Map 2标记和这2个点之间的折线上显示 .
这是我的代码:
//Global array
var pathArray = [];
var cities = [ origin, destination ];
$('#button').on("click", function() {
reverseGeocodeCities(cities);
});
function reverseGeocodeCities(cities) {
$.each(cities, function(index, value) {
geocoder.geocode({'address': value}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
addMarkerCity(results[0].geometry.location);
}
});
});
//Create the polyline just after the loop.
addPolyline();
}
function addMarkerCity(cityPosition) {
var currentMarker = map.addMarker({
position: cityPosition
});
//Add the position of the marker into the global pathArray used by addPolylineCity function.
pathArray.push(currentMarker.getPosition());
}
function addPolylineCity() {
console.log(pathArray); //Display "[]" at the first click.
var polyline = map.drawPolyline({
path: pathArray,
});
我对此代码有两个问题:第一个问题是,当用户在按钮上单击一次时,标记会在Google Map 上很好地显示,但不会在两个标记之间显示折线 . 我必须在按钮上单击两次才能使折线可见 . 要创建折线,我使用包含每个标记位置的全局数组pathArray . 它在第一次单击时始终显示一个空数组,然后在第二次单击按钮后显示标记的正确位置 .
第二个问题是我在创建的折线上做了一个简单的符号动画,但是流向改变时间,如果我想做伦敦到纽约,符号应该从伦敦滑到纽约而不是相反(为了简化代码,我删除了这部分 . 请注意,我正在使用Gmaps包装器来使用Google Map功能 .
如果您知道我的代码出错了,感谢您的帮助 .
1 回答
您首先创建折线,然后创建标记,因此折线不会出现
一个例子JSFiddle