谷歌地图API Javascript E

2024-04-27 02:46:20 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我正在构建一个网络应用程序,它使用谷歌地图的API来显示一张地图,上面有一些标记,每次你点击一个标记,它应该显示来自那个位置的5篇文章,这些文章是由谷歌新闻提供的,我对javascript和web开发还很陌生,我已经花了好几个小时独自解决这个问题,我不知道怎么解决。我将保留JS文件和python文件,它们使用flask处理服务器请求,但我确信服务器端没有什么问题。在

js公司:

// Google Map
var map;

// markers for map
var markers = [];

// info window
var info = new google.maps.InfoWindow();

// execute when the DOM is fully loaded
$(function() {

    // styles for map
    // https://developers.google.com/maps/documentation/javascript/styling
    var styles = [

        // hide Google's labels
        {
            featureType: "all",
            elementType: "labels",
            stylers: [
                {visibility: "off"}
            ]
        },

        // hide roads
        {
            featureType: "road",
            elementType: "geometry",
            stylers: [
                {visibility: "off"}
            ]
        }

    ];

    // options for map
    // https://developers.google.com/maps/documentation/javascript/reference#MapOptions
    var options = {
        center: {lat: 42.3770, lng: -71.1256}, // Cambridge, MA
        disableDefaultUI: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        maxZoom: 14,
        panControl: true,
        styles: styles,
        zoom: 13,
        zoomControl: true
    };

    // get DOM node in which map will be instantiated
    var canvas = $("#map-canvas").get(0);

    // instantiate map
    map = new google.maps.Map(canvas, options);

    // configure UI once Google Map is idle (i.e., loaded)
    google.maps.event.addListenerOnce(map, "idle", configure);

});

/**
 * Adds marker for place to map.
 */
function addMarker(place)
{
    // initialize marker
    var marker = new google.maps.Marker({
        position: {lat: place.latitude, lng: place.longitude},
        map: map,
        title: place.place_name + ', ' + place.admin_name1,
        icon: "http://maps.google.com/mapfiles/kml/pal2/icon31.png"
    });

    // add marker with its place to markers array
    markers.push({marker, place});

    index = markers.length - 1

    // add event listener to the marker
    google.maps.event.addListener(markers[index].marker, 'click', showArticles(markers[index]))
}

/**
 * Gets the articles to be displayed
 */
function showArticles(local)
{
    var parameters = {
        geo: local.place.place_name
    };

    // get articles for the place
    json = $.getJSON(Flask.url_for("articles"), parameters);

    // store those articles in a string containing html
    html = "<ul>"

    json.done(function (){

        if(json.responseJSON){
            for (var i = 0; i < json.responseJSON.length; i++){
            html += "<li><a src=\"" + json.responseJSON[i].link + "\">" + json.responseJSON[i].title + "</a></li>";
            }

            html += "</ul>"

            console.log(json.responseJSON)
            console.log(html)

            showInfo(local.marker, html)

        }}).fail(function (){
            showInfo(local.marker, "")
        })

}

/**
 * Configures application.
 */
function configure()
{
    // update UI after map has been dragged
    google.maps.event.addListener(map, "dragend", function() {

        // if info window isn't open
        // http://stackoverflow.com/a/12410385
        if (!info.getMap || !info.getMap())
        {
            update();
        }
    });

    // update UI after zoom level changes
    google.maps.event.addListener(map, "zoom_changed", function() {
        update();
    });

    // configure typeahead
    $("#q").typeahead({
        highlight: false,
        minLength: 1
    },
    {
        display: function(suggestion) { return null; },
        limit: 10,
        source: search,
        templates: {
            suggestion: Handlebars.compile(
                "<div>" +
                "{{place_name}}, {{admin_name1}}, {{postal_code}}" +
                "</div>"
            )
        }
    });

    // re-center map after place is selected from drop-down
    $("#q").on("typeahead:selected", function(eventObject, suggestion, name) {

        // set map's center
        map.setCenter({lat: parseFloat(suggestion.latitude), lng: parseFloat(suggestion.longitude)});

        // update UI
        update();
    });

    // hide info window when text box has focus
    $("#q").focus(function(eventData) {
        info.close();
    });

    // re-enable ctrl- and right-clicking (and thus Inspect Element) on Google Map
    // https://chrome.google.com/webstore/detail/allow-right-click/hompjdfbfmmmgflfjdlnkohcplmboaeo?hl=en
    document.addEventListener("contextmenu", function(event) {
        event.returnValue = true;
        event.stopPropagation && event.stopPropagation();
        event.cancelBubble && event.cancelBubble();
    }, true);

    // update UI
    update();

    // give focus to text box
    $("#q").focus();
}

/**
 * Removes markers from map.
 */
function removeMarkers()
{
    for(var i = 0; i < markers.length; i++){
        markers[i].marker.setMap(null)
    }

    markers = []
}

/**
 * Searches database for typeahead's suggestions.
 */
function search(query, syncResults, asyncResults)
{
    // get places matching query (asynchronously)
    var parameters = {
        q: query
    };
    $.getJSON(Flask.url_for("search"), parameters)
    .done(function(data, textStatus, jqXHR) {

        // call typeahead's callback with search results (i.e., places)
        asyncResults(data);
    })
    .fail(function(jqXHR, textStatus, errorThrown) {

        // log error to browser's console
        console.log(errorThrown.toString());

        // call typeahead's callback with no results
        asyncResults([]);
    });
}

/**
 * Shows info window at marker with content.
 */
function showInfo(marker, content)
{
    // start div
    var div = "<div id='info'>";
    if (typeof(content) == "undefined")
    {
        // http://www.ajaxload.info/
        div += "<img alt='loading' src='/static/ajax-loader.gif'/>";
    }
    else
    {
        div += content
    }

    // end div
    div += "</div>";

    // set info window's content
    info.setContent(div);

    // open info window (if not already open)
    info.open(map, marker);
}

/**
 * Updates UI's markers.
 */
function update()
{
    // get map's bounds
    var bounds = map.getBounds();
    var ne = bounds.getNorthEast();
    var sw = bounds.getSouthWest();

    // get places within bounds (asynchronously)
    var parameters = {
        ne: ne.lat() + "," + ne.lng(),
        q: $("#q").val(),
        sw: sw.lat() + "," + sw.lng()
    };
    $.getJSON(Flask.url_for("update"), parameters)
    .done(function(data, textStatus, jqXHR) {

       // remove old markers from map
       removeMarkers();

       // add new markers to map
       for (var i = 0; i < data.length; i++)
       {
           addMarker(data[i]);
       }
    })
    .fail(function(jqXHR, textStatus, errorThrown) {

        // log error to browser's console
        console.log(errorThrown.toString());
    });

};

Python:

^{pr2}$

这是我运行页面时控制台上出现的错误,如果需要,我可以留下一个指向运行应用程序的服务器的链接。 enter image description here


Tags: todivinfoeventjsonmapforvar
1条回答
网友
1楼 · 发布于 2024-04-27 02:46:20

以下代码在第93行返回未定义的值:

// get articles for the place
json = $.getJSON(Flask.url_for("articles"), parameters);

当您尝试访问时,错误发生在第100行json.responseJSON. 您使用的条件句需要更像以下其中一种:

^{pr2}$

或者

if ( json.responseJSON.length > 0 )

相关问题 更多 >