如何在谷歌地图中连接两个点..?

时间:2013-04-02 20:08:12

标签: javascript google-maps google-maps-api-3

    function createLine()
{

        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(7.5653, 80.4303);
        var mapOptions = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("directionpanel"), mapOptions);

        var address = document.getElementById('startvalue').value;
        var address2 = document.getElementById('endvalue').value;

        var temp, temp2;

        geocoder.geocode({ 'address': address }, function (results, status) {
            temp = results[0].geometry.location;
        });
        geocoder.geocode({ 'address': address2 }, function (results, status) {
            temp2 = results[0].geometry.location;
        });

        var route = [
          new google.maps.LatLng(temp),
          new google.maps.LatLng(temp2)
        ];


    var polyline = new google.maps.Polyline({
        path: route,
        strokeColor: "#ff0000",
        strokeOpacity: 0.6,
        strokeWeight: 5
    });

    polyline.setMap(map);


}

我想绘制一条直线来连接两个点,我不会计算该行距离。我尝试使用此代码连接点的方式,但它没有用。请帮助我..

1 个答案:

答案 0 :(得分:4)

地理编码是异步的。尝试这样的事情(从第一个回调中调用第二个地理编码器操作,在第二个回调中使用两者的结果)。

function createLine()
{

    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(7.5653, 80.4303);
    var mapOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("directionpanel"), mapOptions);

    var address = document.getElementById('startvalue').value;
    var address2 = document.getElementById('endvalue').value;

    var temp, temp2;

    geocoder.geocode({ 'address': address }, function (results, status) {
        temp = results[0].geometry.location;
        geocoder.geocode({ 'address': address2 }, function (results, status) {
            temp2 = results[0].geometry.location;

        var route = [
          temp,
          temp2
        ];

        var polyline = new google.maps.Polyline({
            path: route,
            strokeColor: "#ff0000",
            strokeOpacity: 0.6,
            strokeWeight: 5
        });

        polyline.setMap(map);
        });
    });
}

working example