google.maps.setCenter()latitude&通过jquery.ajax()请求经度

时间:2011-09-08 14:17:06

标签: jquery json jquery-ui google-maps jquery-ui-autocomplete

我有一个jquery自动完成ui元素,显示了一个火车站列表。当用户从自动完成列表中选择一个工作站时,该功能应该从数据库中返回一组纬度/坐标,并将地图重新​​放在那些坐标上?

在这段代码中,有人发现我的代码错误吗?

// make a json request to get the map data from the Map action
$(function() {         
    $.getJSON("/Home/Map", initialise);
});

var infowindow = new google.maps.InfoWindow({content: "EMPTY"});




function initialise(mapData) {

var latlng = new google.maps.LatLng(54.466667, -3.233333);

var myOptions = {
    zoom: 5,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    mapTypeControlOptions: {

        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
    },
    scaleControl: true,
    streetViewControl: false

};


var map = new google.maps.Map($("#map")[0],
myOptions);


   $.each(mapData, function (i, location) {
       setupLocationMarker(map, location);
   });

//Autocomplete 
 $(function () {
        $("#tags").autocomplete({
            source: "/Home/StationsList",
            minLength: 2,
            select: function (event, ui) {
                jQuery.ajax({
                    url: "Home/GetStationLatLong/" + ui.item.value,
                    dataType: "json",
                    success: function (data) {
                        map.setCenter(new google.maps.latLng(data.latitude, data.longitude));
                    }                       
                });
            }
        });

    });

}

function setupLocationMarker(map, location) {

var latlng = new google.maps.LatLng(location.Latitude, location.Longitude);

var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title: location.Name

});

google.maps.event.addListener(marker, 'click', function () {
    infowindow.setContent('<h2>' + location.Name + '</h2>');

    infowindow.open(map, marker);


    $("#info").text(location.Name);
});     

}

通过“Home / GetStationLatLong”请求从服务器返回的JSON如下所示

[{"latitude":53.66314,"longitude":-1.48149}]

3 个答案:

答案 0 :(得分:5)

map.setCenter(new google.maps.LatLng(data[0].latitude, data[0].longitude));

答案 1 :(得分:2)

也许你正在寻找这个

success: function (data){
  //map.setCenter(new google.maps.latLng(coordinates[0].latitude, data.longitude));
   var coordinates = $.parseJON(data);
   map.panTo(new google.maps.LatLng(coordinates[0].latitude, coordinates[0].longitude));
}

答案 2 :(得分:0)

成功函数应该是:

success: function(data) {
    google.maps.setCenter(new google.maps.latLng(data.latitude, data.longitude));
}