繁体   English   中英

Google Maps API v3出现问题

[英]Issue with Google Maps API v3

我正在尝试通过Google Maps API完成以下任务:

  • 在地图上显示to_address作为标记
  • 获取用户位置
  • 根据gps /用户输入提供的信息生成并显示路线

我已经使最后两个工作正常。 我现在遇到的问题是,如果未提供位置,则在地图to_address显示为标记。

这是我正在使用的代码。 请记住,最后两个步骤按预期工作。 我知道我可以使用latlng完成此操作,但这不是我的选择。 我需要提供一个地址。

var geocoder;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var to_pos;
var to_address = '11161 84th ave delta bc';

function initialize() {

    directionsDisplay = new google.maps.DirectionsRenderer();


    geocoder = new google.maps.Geocoder();

    geocoder.geocode({
        'address': to_address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            to_pos = results[0].geometry.location;
        }
    });

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

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

    var control = document.getElementById('d_options');

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

            var infowindow = new google.maps.Marker({
                position: pos,
                map: map,
                title: "You"
            });

            map.setCenter(pos);
            $('#from').val(pos);
            $('#d_options').trigger('collapse');
            calcRoute();

        }, function () {
            handleNoGeolocation(true);
        });
    }
}

function calcRoute() {
    var start = document.getElementById('from').value;
    var end = to_address;
    $('#results').show();
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}


google.maps.event.addDomListener(window, 'load', initialize);

地理编码使用异步请求。 您必须在geocode()的回调中创建标记

geocoder.geocode({
        'address': to_address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var to_pos = results[0].geometry.location;

            new google.maps.Marker({
                position: new google.maps.LatLng(to_pos.lat(),to_pos.lng()),
                map: map,
                title: "Destination"
            });
        }
    });

暂无
暂无

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

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