简体   繁体   English

使用谷歌地图API和phonegap显示当前位置+方向?

[英]Showing current location + directions using google maps API and phonegap?

I have following requirements 我有以下要求

  1. Show directions from point of origin to destination 显示从起点到目的地的路线
  2. Show user's current location. 显示用户的当前位置。

I am creating a map with directions and then displaying user's current location on that. 我正在创建一个带有路线的地图,然后在其上显示用户的当前位置。

function showDirection(orgn, dstntn)
{
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();

    var map = new google.maps.Map(document.getElementById('displayMap'), {
        zoom : 7,
        mapTypeId : google.maps.MapTypeId.ROADMAP
    });

    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('displayDirections'));

    var request = {
        origin : orgn,
        destination : dstntn,
        travelMode : google.maps.DirectionsTravelMode.WALKING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
    var win = function(position) {
            var lat = position.coords.latitude;
            var long = position.coords.longitude;
            var myLatlng = new google.maps.LatLng(lat, long);
            var iconimage="images/current_location_small.png";
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map
                icon: iconimage
            });

            marker.setMap(map);
     };

     var fail = function(e) {
            alert('Can\'t retrieve position.\nError: ' + e);
        };

     var watchID = navigator.geolocation.getCurrentPosition(win, fail);
}

The above code works fine if the user is within the map created for showing directions, but if the user is out of the map area, his current location is not shown. 如果用户位于为显示路线而创建的地图内,则上述代码可以正常工作,但如果用户不在地图区域内,则不会显示其当前位置。

I somehow want all the three points 1. origin, 2. destination and 3. user location to fit on the map. 我不知何故想要三个点1.起点,2。目的地和3.用户位置以适应地图。 Is there a way I can zoom the map out to fit all three points, or create original map in a way that all three points are visible. 有没有办法可以缩放地图以适应所有三个点,或者以所有三个点都可见的方式创建原始地图。

Add the following after marker.setMap(map); marker.setMap(map);之后添加以下内容marker.setMap(map);

marker.setMap(map);
//Add these lines to include all 3 points in the current viewport
var bounds = new google.maps.LatLngBounds();
bounds.extend(orgn);
bounds.extend(dstntn);
bounds.extend(myLatlng);
map.fitBounds(bounds);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM