0

I've finished search and it appears to give the correct JSON output. When I display the map all the markers come up correctly but when I enter a new location or Postal code in the query box nothing happens - no dropdown menu or even "no places found yet" message. I'd love some help here. https://cs50-applebyoz.cs50.io/ My jscript code is:

/* global google */
/* global _ */
/**
* scripts.js
*
* Computer Science 50
* Problem Set 8
*
* Global JavaScript.
*/

// 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, Massachusetts
    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)
{
// Add marker
var marker = new MarkerWithLabel({
icon: "http://maps.google.com/mapfiles/kml/pal2/icon31.png",    
position: new google.maps.LatLng(place.latitude, place.longitude),
map: map,
labelContent: place.place_name + ", " + place.admin_name1 
          + ", " + place.postal_code,
labelAnchor: new google.maps.Point(20, 0),
labelClass: "label"
});    

// check for marker being clicked
google.maps.event.addListener(marker, "click", function() 
{
    showInfo(marker);
    $.getJSON("articles.php", 
    {
        geo: place.postal_code
    })

    .done(function(data, textStatus, jqXHR) 
    {
        // if there is no news, tell user no news
        if (data.length === 0)
        {
            showInfo(marker, "No News.");
        }
        // else if there is news, displays news in unordered list
        else
        {
            // start unordered list
            var ul = "<ul>";    

            // create template
            var template = _.template("<li><a href = '<%- link %>' target = '_blank'><%- title %></a></li>");

            // use template to insert content
            for (var i = 0, n = data.length; i < n; i++)
            {
                ul += template(
                    {
                    link: data[i].link,
                    title: data[i].title
                    }); 
            }

            // end unordered list
            ul += "</ul>";  

            // show news
            showInfo(marker, ul);
        }
    });
});

// add marker to global variable markers
markers.push(marker);
}

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

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

// remove markers whilst dragging
google.maps.event.addListener(map, "dragstart", function() {
    removeMarkers();
});

// configure typeahead
// https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md
$("#q").typeahead({
    autoselect: true,
    highlight: true,
    minLength: 2
},
{
    source: search,
    templates: {
        empty: "no places found yet",
        suggestion: function(data) {
            return "<p>" + data.place_name + ", " + data.admin_name1 + " " + data.postal_code + "</p>"
    }
    }
});

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

    // ensure coordinates are numbers
    var latitude = (_.isNumber(suggestion.latitude)) ? suggestion.latitude : parseFloat(suggestion.latitude);
    var longitude = (_.isNumber(suggestion.longitude)) ? suggestion.longitude : parseFloat(suggestion.longitude);

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

    // update UI
    update();
});

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

// 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();
}

/**
 * Hides info window.
 */
function hideInfo()
{
    info.close();
}

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

// reset length to 0
markers.length = 0;
}

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

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

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

/**
 * 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='img/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("update.php", 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());
 });
 }
2

Nothing wrong with your scripts.js from what I can see.

Try to clear your browser's cache or something.

If I paste your entire file in place of my scripts.js, your code works.

So maybe your problem is elsewhere?

0

I tried clearing the cache in Firefox with no improvement. I then tried it in IE and it worked fine. I closed Firefox and restarted and it now works fine there. Go figure! Like every computer helpline operator says: "Have you restarted your computer?!"

Thanks for your help Yuri.

1
  • Great! Please accept your own answer or my answer to this question, so it can be closed. Otherwise it will forever roam this forum as a Zombie open question! – Yuri Laguardia Nov 18 '16 at 13:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .