如何使用谷歌地图的JavaScript API请求从当前位置到目的地

问题描述 投票:-1回答:1

我一直在探索谷歌地图API的JavaScript网页和我陷入试图显示用户的当前位置与目的地之间的路线。

我能够当它们被使用经纬度(纬度,经度)预定义的两个位置之间的显示方向。我也能够找到用户的当前位置。我似乎无法做到这两点。

function initMap() {

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
    }
    else {
        alert("Geolocation not supported");
    }

}

function locationSuccess(position) {

    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();
    var trafficLayer = new google.maps.TrafficLayer();

    var myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    var LA = new google.maps.LatLng(34.0522, -118.2437);

    var mapOptions = {
        zoom: 8,
        center: {lat: 34.2805, lng: -119.2945}
    };

    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
    directionsDisplay.setMap(map);
    trafficLayer.setMap(map);

    //This will mark the current location if found
    // var myLocationMarker = new google.maps.Marker({
    //     position: myLocation,
    //     map: map,
    //     title: 'Current location'
    // });

    map.setCenter(myLocation);

    var request = {
        origin: myLocation,
        destination: LA,
        travelMode: 'DRIVING'
    };

    directionsService.route(request, function (result, status) {
        if (status == google.maps.DirectionsStatus.OK)
            directionsDisplay.setDirections(result);
    });


}

function locationError() {
    alert("Couldn't get location");
}
javascript google-maps directions google-geolocation
1个回答
0
投票

我不知道是什么的问题是,是阻止你实现你的目标 - 我想上面的代码,它似乎工作 - 因为它太冷在车库里我有一个小游戏工作,创造了一个小的演示;也许尽管你或其他人可能会发现下面的有用吗?

最初,当调用navigator.getCurrentLocation与用户的位置解析使用返回position对象的地图加载,以形成地图的中心位置。特别是在这种情况下隐藏默认的标记 - 到预先定义destination路线然后使用Directions服务与修改后的选项参数计算。之所以隐藏标记是因为他们不暴露任何事件,因此,我们不能绑定任何听众给他们,让我们加入我们自己的。所添加的标记允许动态地重新计算出的路线(也可以将实际的路线本身)

方向的文本版本可通过点击这两个标志之一。

destination是在英国伯明翰。如果你是outwith英国,这可能不是没有编辑这个位置立即开始工作。此外,有效的API密钥是必需的。

<!DOCTYPE html>
<html>
    <head>
        <title>Google Maps: Directions from my location to...</title>
        <meta charset='utf-8' />
        <style>
            body,
            html { height:100%;margin:0;padding:0;box-sizing:border-box; }
            #map { width:100%;height:100vh; margin:auto;float:none; }
            #info{ display:none;padding:0.25rem;margin:1rem;background:white;font-size:0.75rem!important; }
        </style>
        <script>
            let map;
            let marker;
            let infoWindow;
            let oDir;
            let oTraf;
            let oDisp;
            let oReq;
            let destination={ lat:52.477068, lng:-1.911663 };

            const modes={
                walk:'WALKING',
                bike:'BICYCLING',
                car:'DRIVING',
                pub:'TRANSIT'
            };
            const advReqOptions={
                provideRouteAlternatives:true,
                optimizeWaypoints:true,
                avoidFerries:true,
                avoidHighways:false,
                avoidTolls:false
            };



            function initMap(){
                /* utility to add a new marker and assign listeners to it */
                const addmarker=function( pos, type, colour ){
                    marker=new google.maps.Marker({
                        icon:'//maps.google.com/mapfiles/ms/icons/'+colour+'-pushpin.png',
                        type:type,
                        draggable:true,
                        position:pos,
                        map:map
                    });
                    google.maps.event.addListener( marker, 'click', function(e){
                        infoWindow.getContent().style.display='block';
                        infoWindow.setPosition( this.getPosition() );
                        infoWindow.open( map );
                    });
                    google.maps.event.addListener( marker, 'dragend', calculateroute );
                };

                /* callback function when markers are dragged and the route is re-calculated */
                const calculateroute=function(e){
                    oReq={
                        origin:this.type=='start' ? e.latLng : oReq.origin,
                        destination:this.type=='finish' ? e.latLng : oReq.destination,
                        travelMode:modes.car
                    };
                    oDir.route( Object.assign( oReq, advReqOptions ), callback );
                };

                /* process the route response */
                const callback=function(r,s){
                    if( s === 'OK' ) oDisp.setDirections( r );
                    else evtGeoFailure( s );
                }

                /* Main callback invoked when the user's location has been identified */
                const evtGeoSuccess=function(p){
                    /* create the map */
                    let location={
                        lat: parseFloat( p.coords.latitude ),
                        lng: parseFloat( p.coords.longitude )
                    };
                    let options= {
                        zoom: 16,
                        center:location,
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    };
                    let routeoptions={
                        suppressMarkers:true,
                        draggable:true,
                        map:map
                    };

                    /* create the map object */
                    map = new google.maps.Map( document.getElementById('map'), options );

                    /* add draggable markers to the start and end of pre-defined route */
                    addmarker( location, 'start', 'grn' );
                    addmarker( destination, 'finish', 'red' );

                    /* display the textual directions in an infowindow which opens on marker click */
                    infoWindow = new google.maps.InfoWindow({ maxWidth:450, disableAutoPan:false });
                    infoWindow.setContent( document.getElementById('info') );


                    /* create the objects required for the directions calculations */
                    oDir=new google.maps.DirectionsService();
                    oDisp=new google.maps.DirectionsRenderer( routeoptions );
                    oTraf=new google.maps.TrafficLayer();


                    /* construct the initial request */
                    oReq={
                        origin:location,
                        destination:destination,
                        travelMode:modes.car
                    };

                    /* go get the directions... */
                    oDisp.setMap( map );
                    oTraf.setMap( map );
                    oDisp.setPanel( infoWindow.getContent() );
                    oDir.route( Object.assign( oReq, advReqOptions ), callback );
                };


                const evtGeoFailure=function(e){ console.info( 'you broke the internets: %s', e ) };
                const config={ maximumAge:60000, timeout:5000, enableHighAccuracy:true };

                if( navigator.geolocation ) navigator.geolocation.getCurrentPosition( evtGeoSuccess, evtGeoFailure, config );
            }
        </script>
        <script src='//maps.googleapis.com/maps/api/js?key=<<APIKEY>>&callback=initMap' async defer></script>
    </head>
    <body>
        <div id='map'></div>
        <div id='info'></div>
    </body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.