如何在JavaScript中的Google地图中的两个标记之间选择方向

时间:2018-08-10 05:55:19

标签: javascript google-maps

我正在使用以下代码显示带有标记的地图。如何获得两个选定的标记,然后显示路线?

我想从前端选择两个点,然后显示它们之间的路线。

应该可以这样工作- 用户将单击一个标记,它将调用一个函数并将拉特隆保存为起点,然后,当选择另一个标记时,它将拉特隆保存为终点,然后在两个点之间绘制一条路线。当再次选择标记时,终点将成为起点,当前标记将成为终点。等等...

function initMap() {
    //cordinates for center dot
    var citymap = {
        chicago: {
            center: { lat: -33.91722, lng: 151.23064 },
            population: 2714856
        }
    };
    //create map in html its center as lat long
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: new google.maps.LatLng(-33.91722, 151.23064),
        mapTypeId: 'roadmap'
    });
    //center dor creation
    for (var city in citymap) {
        // Add the circle for this city to the map.
        var cityCircle = new google.maps.Circle({
            strokeColor: '#98FB98',
            strokeOpacity: 0.6,
            strokeWeight: 2,
            fillColor: '#98FB98',
            fillOpacity: 0.12,
            map: map,
            center: citymap[city].center,
            radius: 100*4.3
        });
    }

    //Markers list will be replaced by loop after data input
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(-33.91722, 151.23064),
        icon: 'https://maps.google.com/mapfiles/kml/pal4/icon25.png',
        map: map
    });
    var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
    var iconBase1 = 'https://maps.google.com/mapfiles/kml/pal4/';
    var iconBase2 = 'https://maps.google.com/mapfiles/kml/paddle/';
    var iconBase3 = 'https://maps.google.com/mapfiles/kml/pal2/';
    var iconBase4 = 'https://maps.google.com/mapfiles/kml/pal3/';

    var icons = {
        parking: {
            icon: iconBase3 + 'icon10.png'
        },
        library: {
            icon: iconBase4 + 'icon48.png'
        },
        info: {
            icon: iconBase4 + 'icon21.png'
        }
    };
    marker.addListener("click", function () {
        alert('Hi');
    });
    var features = [{
        position: new google.maps.LatLng(-33.91721, 151.22630),
        type: 'info'
    },{
        position: new google.maps.LatLng(-33.91818154739766, 151.2346203981781),
        type: 'parking'
    }, {
        position: new google.maps.LatLng(-33.91727341958453, 151.23348314155578),
        type: 'library'
    }];

    // Create markers.
    features.forEach(function(feature) {
        var marker = new google.maps.Marker({
            position: feature.position,
            icon: icons[feature.type].icon,
            map: map
        });
        marker.addListener("click", function () {
            alert(marker.getPosition());
            marker.icon = 'https://maps.google.com/mapfiles/kml/pal3/icon20.png'
        });
    });

    calcRoute();

}

在这里,我需要从每次标记点击中获取反馈,然后相应地计算路线。

0 个答案:

没有答案