Google Maps:将额外的参数传递给 GeoCoder for InfoWindows



这是我的第一篇文章。我完全陷入困境,可以使用一些帮助将infoWindows添加到Google地图。我实际要使用的数据(不是我在这里使用的 API)没有 lat/lon 并且有多个值。

infoWindow之前一切都很好,但我无法将任何其他参数传递到geocoder回调中。提前感谢您的帮助!

功劳归于明辉:http://goo.gl/zvAKZ8。我的为信息窗口使用不同的数据,可能有大约 30 个标记。

这是相关的代码 JS FIDDLE:

var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 3,
    center: new google.maps.LatLng(0, 0),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker;
var i;
var mapData;
var locations = [];
$(document).ready(function () {
    $.ajax({
    url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk',
        async: false,
        success: function (mapData) {
        locations.push(mapData.name);
    }
});
    initialize();
});
function initialize() {
    setMarkers(map, locations);
}
function setMarkers(map, address) {
    for (var i = 0; i < address.length; i++) {
        setMarker(map, address[i])
    }
}
function setMarker(map, address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'address': address
    },
    function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map
            });
            google.maps.event.addListener(marker,
                "click", function () {
                    //HAVING THE PROBLEM HERE. Not sure how to separate this from the callback. 
                  infowindow.setContent(mapData.main.temp);
                    // But this works if you run it:
                //infowindow.setContent(address);
                infowindow.open(map, marker);
            });
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
} 

您已将 myData 声明为全局变量。

但是在这里,您将mapData作为ajax成功回调的参数。

$(document).ready(function () {
    $.ajax({
    url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk',
        async: false,
        success: function (mapData) {  //locally scoped which can't override
        locations.push(mapData.name);                
        }
});

这不会覆盖全局变量。

而是像这样做

var gmapData = {};

并像使用它一样使用

$(document).ready(function () {
    $.ajax({
    url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk',
        async: false,
        success: function (mapData) {
        locations.push(mapData.name);            
        gmapData = mapData; //assign mapData to global variable
        }
});

现在在infoWindow中使用

 google.maps.event.addListener(marker, "click", function () {   
            //infowindow.setContent() will accept only string 
            //whereas temp is numeric, so convert to string                 
        infowindow.setContent(gmapData.main.temp.toString());
        infowindow.open(map, marker);
});

JSFiddle

最新更新