在JSON中从URL动态添加标记到Google Map

时间:2018-02-19 18:11:40

标签: json ajax google-maps

我需要一种基于存储在外部JSON文件中的地理坐标(纬度/经度),动态地将标记添加到Google Map的方法。该方法需要调用url以显示每个位置的自定义标记。最终目标是根据观察到的条件为每个位置显示特定于天气的图标。

我已经有一个JSON调用在地图窗口中显示天气信息(见下文):

function initMap() {
    var hc = {lat: 40.466442, lng: -85.362709};
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 12,
        center: hc
    });

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

    var iconBase = "http://icons.wxug.com/i/c/k/cloudy.gif";
        var marker = new google.maps.Marker({
            position: hc,
            map: map,
            title: 'Hartford City',
            icon: iconBase
        });

    marker.addListener('click', function() {
        infowindow.open(map, marker);
    });
}

var downloadJSON = function() {
    $.getJSON( "ajax/GeoObs.json?_="+new Date().getTime(), function( data ) {
        var items = [];
        items.push( "<li id='Weather'>Station: " + data.features[0].properties.Station + "</li>");
        items.push( "<li id='Weather'>Time: " + data.features[0].properties.Time + "</li>");
        items.push( "<li id='Weather'>Weather: " + data.features[0].properties.Weather + "</li>");
        items.push( "<li id='Weather'>Temp: " + data.features[0].properties.Temp + "</li>");
        items.push( "<li id='Weather'>Wind: " + data.features[0].properties.Wind + "</li>");
        obj = $('<div>').append($( "<ul/>", { class: "my-new-list", html: items.join("") })).html();
        initMap();
    });
}

我如何添加第二个$ .getJSON来显示JSON输出中URL的地图标记?

{"features": [{"geometry": {"coordinates": [-85.362709, 40.466442], "type": "Point"}, "properties": {"24-hr Precip": "0.00", "Dewpoint": "26", "Pressure": "30.23", "Ptrend": "+", "Station": "KINHARTF10", "Temp": "30.2 F (-1.0 C)", "Time": "Last Updated on January 24, 12:56 PM EST", "Weather": "Overcast", "Wind": "From the SE at 4.5 MPH Gusting to 6.9 MPH", "icon": "cloudy",
        "icon_url": "http://icons.wxug.com/i/c/k/cloudy.gif"}, "type": "Feature"}], "type": "FeatureCollection"}

1 个答案:

答案 0 :(得分:0)

你应该在downloadJSON和“ajax / GeoObs.json?”中添加lat和lng作为参数。例如ajax / GeoObs.json?_ = date&amp; lat = xx&amp; lng = xxx。你必须在你的页面中添加“&amp; lat = xx&amp; lng = xxx”并调用“downloadJSON(lat,lng)”并创建第二个标记