Google Maps API v3问题

时间:2012-03-30 23:46:51

标签: javascript jquery html google-maps google-maps-api-3

我正在尝试使用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);

1 个答案:

答案 0 :(得分:0)

地理编码使用异步请求。您必须在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"
            });
        }
    });