How to connect two points in Google map..?

2019-01-12 01:25发布

问题:

    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);


}

I want to draw a direct line to connect two points and i wont to calculate that line distance.any way i try to connect points using this code but it didn't work.Please help me..

回答1:

Geocoding is asynchronous. Try something like this (call the second geocoder operation from the call back of the first, use the results of both inside the call back of the second).

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