Advertisement
DragonOsman

Mashup scripts.js

May 3rd, 2017
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Google Map
  2. var map;
  3.  
  4. // markers for map
  5. var markers = [];
  6.  
  7. // info window
  8. var info = new google.maps.InfoWindow();
  9.  
  10. // execute when the DOM is fully loaded
  11. $(function() {
  12.  
  13.     // styles for map
  14.     // https://developers.google.com/maps/documentation/javascript/styling
  15.     var styles = [
  16.  
  17.         // hide Google's labels
  18.         {
  19.             featureType: "all",
  20.             elementType: "labels",
  21.             stylers: [
  22.                 {visibility: "off"}
  23.             ]
  24.         },
  25.  
  26.         // hide roads
  27.         {
  28.             featureType: "road",
  29.             elementType: "geometry",
  30.             stylers: [
  31.                 {visibility: "off"}
  32.             ]
  33.         }
  34.  
  35.     ];
  36.  
  37.     // options for map
  38.     // https://developers.google.com/maps/documentation/javascript/reference#MapOptions
  39.     var options = {
  40.         center: {lat: 42.3770, lng: -71.1256}, // Cambridge, Massachusetts
  41.         disableDefaultUI: true,
  42.         mapTypeId: google.maps.MapTypeId.ROADMAP,
  43.         maxZoom: 14,
  44.         panControl: true,
  45.         styles: styles,
  46.         zoom: 13,
  47.         zoomControl: true
  48.     };
  49.  
  50.     // get DOM node in which map will be instantiated
  51.     var canvas = $("#map-canvas").get(0);
  52.  
  53.     // instantiate map
  54.     map = new google.maps.Map(canvas, options);
  55.  
  56.     // configure UI once Google Map is idle (i.e., loaded)
  57.     google.maps.event.addListenerOnce(map, "idle", configure);
  58.  
  59. });
  60.  
  61. /**
  62.  * Adds marker for place to map.
  63.  */
  64. function addMarker(place)
  65. {
  66.     var myLatLng = {lat: place["latitude"], lng: place["longitude"]};
  67.     var marker = new google.maps.Marker({
  68.         position: myLatLng,
  69.         map: map
  70.     });
  71.    
  72.     marker.setLabel(place["place_name"] + ", " + place["admin_name1"]);
  73.    
  74.     // lines 75 through 122 inspired by OP's code at https://cs50.stackexchange.com/questions/24770/more-than-10-markers-show-up-for-mashup
  75.     geo = {geo: place["place_name"] + ", " + place["admin_name1"] + ", " + place["postal_code"]};
  76.     // get the articles associated with the place
  77.     $.getJSON(Flask.url_for("articles"), geo)
  78.         .done(function(data, textStatus, jqXHR) {
  79.             // iterate through the data and get the relevant information
  80.             // create element for unordered list
  81.             var content = document.createElement("ul");
  82.             for (i = 0; i < data.length; i++)
  83.             {
  84.                 // create item element and the link
  85.                 var item = document.createElement("li");
  86.                
  87.                 // create html tag <a>
  88.                 var a = document.createElement("a");
  89.                
  90.                 // create text node
  91.                 var title = document.createTextNode(data[i].title);
  92.                
  93.                 // insert hyperlink into a
  94.                 a.setAttribute("href", data[i].link);
  95.                
  96.                 // append text to a
  97.                 a.appendChild(title);
  98.                
  99.                 // set item's value
  100.                 item.appendChild(a);
  101.                
  102.                 // append item to the list
  103.                 content.appendChild(item);
  104.             }
  105.             // add listener for the click event
  106.             google.maps.event.addListener(marker, "click", function() {
  107.                 showInfo(marker, content.innerHTML);
  108.             });
  109.         })
  110.         .fail(function(jqXHR, textStatus, errorThrown) {
  111.             // log error to browser's console
  112.             console.log(errorThrown.toString());
  113.            
  114.             // return undefined content to the showInfo function
  115.             var content = undefined;
  116.            
  117.             // call show info with no content which will cause the gif to appear
  118.             google.maps.event.addListener(marker, "click", function() {
  119.             showInfo(marker,content);
  120.         });
  121.     });
  122.     markers.push(marker);
  123. }
  124.  
  125. /**
  126.  * Configures application.
  127.  */
  128. function configure()
  129. {
  130.     // update UI after map has been dragged
  131.     google.maps.event.addListener(map, "dragend", function() {
  132.  
  133.         // if info window isn't open
  134.         // http://stackoverflow.com/a/12410385
  135.         if (!info.getMap || !info.getMap())
  136.         {
  137.             update();
  138.         }
  139.     });
  140.  
  141.     // update UI after zoom level changes
  142.     google.maps.event.addListener(map, "zoom_changed", function() {
  143.         update();
  144.     });
  145.  
  146.     // configure typeahead
  147.     $("#q").typeahead({
  148.         highlight: false,
  149.         minLength: 1
  150.     },
  151.     {
  152.         display: function(suggestion) { return null; },
  153.         limit: 10,
  154.         source: search,
  155.         templates: {
  156.             suggestion: Handlebars.compile(
  157.                 "<div>" +
  158.                 "{{ place_name }}, {{ admin_name1 }}, {{ postal_code }}" +
  159.                 "</div>"
  160.             )
  161.         }
  162.     });
  163.  
  164.     // re-center map after place is selected from drop-down
  165.     $("#q").on("typeahead:selected", function(eventObject, suggestion, name) {
  166.  
  167.         // set map's center
  168.         map.setCenter({lat: parseFloat(suggestion.latitude), lng: parseFloat(suggestion.longitude)});
  169.  
  170.         // update UI
  171.         update();
  172.     });
  173.  
  174.     // hide info window when text box has focus
  175.     $("#q").focus(function(eventData) {
  176.         info.close();
  177.     });
  178.  
  179.     // re-enable ctrl- and right-clicking (and thus Inspect Element) on Google Map
  180.     // https://chrome.google.com/webstore/detail/allow-right-click/hompjdfbfmmmgflfjdlnkohcplmboaeo?hl=en
  181.     document.addEventListener("contextmenu", function(event) {
  182.         event.returnValue = true;
  183.         event.stopPropagation && event.stopPropagation();
  184.         event.cancelBubble && event.cancelBubble();
  185.     }, true);
  186.  
  187.     // update UI
  188.     update();
  189.  
  190.     // give focus to text box
  191.     $("#q").focus();
  192. }
  193.  
  194. /**
  195.  * Removes markers from map.
  196.  */
  197. function removeMarkers()
  198. {
  199.     for (var i = 0; i < markers.length; i++)
  200.     {
  201.         markers[i].setMap(null);
  202.     }
  203.     markers = [];
  204. }
  205.  
  206. /**
  207.  * Searches database for typeahead's suggestions.
  208.  */
  209. function search(query, syncResults, asyncResults)
  210. {
  211.     // get places matching query (asynchronously)
  212.     var parameters = {
  213.         q: query
  214.     };
  215.     $.getJSON(Flask.url_for("search"), parameters)
  216.     .done(function(data, textStatus, jqXHR) {
  217.      
  218.         // call typeahead's callback with search results (i.e., places)
  219.         asyncResults(data);
  220.     })
  221.     .fail(function(jqXHR, textStatus, errorThrown) {
  222.  
  223.         // log error to browser's console
  224.         console.log(errorThrown.toString());
  225.  
  226.         // call typeahead's callback with no results
  227.         asyncResults([]);
  228.     });
  229. }
  230.  
  231. /**
  232.  * Shows info window at marker with content.
  233.  */
  234. function showInfo(marker, content)
  235. {
  236.     // start div
  237.     var div = "<div id='info'>";
  238.     if (typeof(content) == "undefined")
  239.     {
  240.         // http://www.ajaxload.info/
  241.         div += "<img alt='loading' src='/static/ajax-loader.gif'/>";
  242.     }
  243.     else
  244.     {
  245.         div += content;
  246.     }
  247.  
  248.     // end div
  249.     div += "</div>";
  250.  
  251.     // set info window's content
  252.     info.setContent(div);
  253.  
  254.     // open info window (if not already open)
  255.     info.open(map, marker);
  256. }
  257.  
  258. /**
  259.  * Updates UI's markers.
  260.  */
  261. function update()
  262. {
  263.     // get map's bounds
  264.     var bounds = map.getBounds();
  265.     var ne = bounds.getNorthEast();
  266.     var sw = bounds.getSouthWest();
  267.  
  268.     // get places within bounds (asynchronously)
  269.     var parameters = {
  270.         ne: ne.lat() + "," + ne.lng(),
  271.         q: $("#q").val(),
  272.         sw: sw.lat() + "," + sw.lng()
  273.     };
  274.     $.getJSON(Flask.url_for("update"), parameters)
  275.     .done(function(data, textStatus, jqXHR) {
  276.  
  277.        // remove old markers from map
  278.        removeMarkers();
  279.  
  280.        // add new markers to map
  281.        for (var i = 0; i < data.length; i++)
  282.        {
  283.            addMarker(data[i]);
  284.        }
  285.     })
  286.     .fail(function(jqXHR, textStatus, errorThrown) {
  287.  
  288.         // log error to browser's console
  289.         console.log(errorThrown.toString());
  290.     });
  291. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement