I am creating a page to do a basic search for breweries and am displaying information pulled from an API about breweries and would like to display the location on a map from the MapQuest API.
I know how to make a static marker, but is it possible to create a marker after a click event that uses the latitude and longitude from the JSON file? So after entering in a search term to populate the results, I want to be able to click a result and then have a marker added to the map. Is this even possible?
picture of my website project
Here is my code for the map:
var L;
window.onload = function() {
L.mapquest.key = 'hidden';
// 'map' refers to a <div> element with the ID map
var map = L.mapquest.map('map', {
center: [38.584487, -90.266699],
layers: L.mapquest.tileLayer('hybrid'),
zoom: 11
});
map.addControl(L.mapquest.control({
position: 'bottomright'
}));
L.marker([38.584487, -90.266699], {
icon: L.mapquest.icons.marker({
primaryColor: '#22407F',
secondaryColor: '#3B5998',
shadow: true,
size: 'sm',
symbol: 'A'
})
})
.bindPopup('Welcome to St. Louis! <br> Find more info here! ')
.addTo(map);
}
-- and my code for displaying each brewery below the map:
// search bar using JS
const breweryList = document.getElementById('result');
const searchBar = document.getElementById('searchBar');
let brewerySpots = [];
searchBar.addEventListener('keyup', (e) => {
const searchString = e.target.value.toLowerCase();
const filteredBreweries = brewerySpots.filter(data => {
return (
data.name.toLowerCase().includes(searchString) ||
data.city.toLowerCase().includes(searchString)
);
});
displayBreweries(filteredBreweries);
});
const loadBreweries = async () => {
try {
const res = await fetch('https://raw.githubusercontent.com/openbrewerydb/openbrewerydb/master/breweries.json');
brewerySpots = await res.json();
displayBreweries(brewerySpots);
} catch (err) {
console.error(err);
}
};
const displayBreweries = (breweries) => {
const htmlString = breweries
.map((brewery) => {
return `
<li class="brewery col">
<h3>${brewery.name}</h3>
<address> Location: ${brewery.street},
${brewery.city}, ${brewery.state}</address>
<p>Type: ${brewery.brewery_type}</p>
<i style='font-size:24px' class='fas' ></i>
</li>`
})
.join('');
breweryList.innerHTML = htmlString;
};
loadBreweries();
It seems like all of the examples and tutorials I have found pertain to clicking on the map to add a marker, but I want to click a hyperlink on my page that will use the latitude and longitude from the JSON data to add a marker.
Here is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
<script src="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.js"></script>
<link type="text/css" rel="stylesheet" href="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.css"/>
<link rel="stylesheet" href="../styles/style.css" />
<title>Beer30!</title>
</head>
<body>
<nav class="navbar">
<a href="#" class="navbar__logo">
<i class="fas fa-beer"></i>
</a>
<div class="navbar__bars">
<i class="fas fa-bars"></i>
</div>
<div class="navbar__menu">
Home
Breweries
About
Sign Up
Log In
</div>
</nav>
<!-- map placeholder -->
<div id="map"></div>
<!-- search field-->
<div class="container" style="width:900px">
<h2 align="center" style="color: rgb(231, 231, 231)">Search for Breweries</h2>
<h4 align="center" style="color: rgb(231, 231, 231)">Use the search field below to filter by city or brewery name!</h4>
<br>
<div id="searchWrapper">
<input type="text" name="searchBar" id="searchBar" placeholder="Search for a brewery" class="form-control">
</div>
<br>
<ul class="list-group" id="result"></ul>
</div>
<br><br>
<hr>
<!-- area to hold list of breweries -->
<select id="breweries-dropdown" name="breweries"></select>
<br><br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script src="../app/script.js"></script>
</body>
</html>
NICE! I used the Untappd API to do something similar several years ago.
I think your link will need to have an index/reference back to the list of breweries so the code can grab the correct lat/lng from the link, place the marker on the map (the same way the initial St Louis marker is added) and recenter on it.
Related
So what I'm trying to do is get data from a stored procedure and put it into a table on my website. When I call the API functions from my JS file (using XML REQUEST), the if statement never runs, and I never get a result back. Im not too sure where my error is because I don't get any error message, I just get no data returned into my table.
Function that calls to API from JS file
function getStudentTopicQuizResult()
{
console.log("step 1");
var req = new XMLHttpRequest();
req.open('POST', 'https://localhost:44303/api/JSON/getStudentTopicQuizResult', true);
req.setRequestHeader('Content-Type', 'application/json');
req.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200)
{
var result = req.response;
console.log("step 2");
}
}
return false;
}
ASP.NET API Functions
[System.Web.Http.HttpPost]
public object getStudentTopicQuizResult()
{
var response = Request.CreateResponse(HttpStatusCode.OK);
string sql = "getStudentTopicQuizResult";
var json = ExecuteSPGetStudentTopicQuizResult(sql);
response.Content = new StringContent(json);
return response;
}
private static string ExecuteSPGetStudentTopicQuizResult(string queryString)
{
string json = "";
string connectionString = ConfigurationManager.AppSettings["dbconn"].ToString();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand(queryString, conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// execute the command
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// iterate through results, printing each to console
while (rdr.Read())
{
json += "{\"name\":\"" + (string)rdr[0].ToString() + " " + (string)rdr[1].ToString() + "\",\"";
json += "\"topic\":\"" + (string)rdr[2].ToString() + "\",\"";
json += "\"score\":\"" + (string)rdr[5].ToString() + "\",\"";
json += "\"ids\":\"" + (string)rdr[3].ToString() + "|" + (string)rdr[4].ToString() + "\"\"},";
Console.WriteLine(json);
}
}
return json;
}
}
SQL stored procedure code
USE [Capstone]
GO
/****** Object: StoredProcedure [dbo].[getStudentTopicQuizResult] Script Date: 3/29/2021 6:01:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[getStudentTopicQuizResult]
AS
BEGIN
select FirstName, LastName, QuizName, [StudentQuizScore].StudentID, [StudentQuizScore].QuizID, QuizScore
from [dbo].[StudentQuizScore]
inner join Student
on Student.StudentID = [StudentQuizScore].StudentID
inner join Quiz
on quiz.QuizID = [StudentQuizScore].QuizID
END
HTML code for website page with table (Script code at bottom)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="apple-touch-icon" sizes="76x76" href="../assets/img/apple-icon.png">
<link rel="icon" type="image/png" href="../assets/img/favicon.png">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title id=tabtitle>
Teacher Home
</title> <!-- dependent on student login -->
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no' name='viewport' />
<!-- Fonts and icons -->
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700,200" rel="stylesheet" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<!-- CSS Files -->
<link href="../assets/css/bootstrap.min.css" rel="stylesheet" />
<link href="../assets/css/now-ui-kit.css?v=1.3.0" rel="stylesheet" />
<!-- CSS Just for demo purpose, don't include it in your project -->
<link href="../assets/demo/demo.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.css">
</head>
<body class="profile-page sidebar-collapse">
<!-- Navbar -->
<nav class="navbar navbar-expand-lg bg-primary fixed-top navbar-transparent " color-on-scroll="400">
<div class="container">
<div class="collapse navbar-collapse justify-content-end" id="navigation" data-nav-image="../assets/img/blurred-image-1.jpg">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="welcome-page.html">Welcome/Overview</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- End Navbar -->
<div class="page-header clear-filter page-header-small" >
<div class="page-header-image" data-parallax="true" style="background-image:url('../assets/img/capstone/space-bg.jpg');">
</div>
<div class="container">
<h1 id="pagetitle" class="title">Class's Future <!-- dependent on student login --></h1>
</div>
</div>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</div>
<div class="col-xl-10 ml-auto mr-auto text-center">
<table class="display" id="example">
<thead>
<tr>
<th>Student Name</th>
<th>Topic</th>
<th>Score</th>
<th>Quiz Response</th>
</tr>
</thead>
</table>
</div>
<footer class="footer">
<div class=" container ">
<nav>
<ul>
<li>
<a href="https://mhs.monroeps.org/" target="_blank">
Masuk High School
</a>
</li>
<li>
<a href="https://classroom.google.com/h" target="_blank">
Google Classroom
</a>
</li>
</ul>
</nav>
<div class="copyright" id="copyright">
©
<script>
document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear()))
</script> Designed and coded by Mike Aiello</a>
</div>
</div>
</footer>
<!-- Core JS Files -->
<script src="../assets/js/core/jquery.min.js" type="text/javascript"></script>
<script src="../assets/js/core/popper.min.js" type="text/javascript"></script>
<script src="../assets/js/core/bootstrap.min.js" type="text/javascript"></script>
<!-- Plugin for Switches, full documentation here: http://www.jque.re/plugins/version3/bootstrap.switch/ -->
<script src="../assets/js/plugins/bootstrap-switch.js"></script>
<!-- Plugin for the Sliders, full documentation here: http://refreshless.com/nouislider/ -->
<script src="../assets/js/plugins/nouislider.min.js" type="text/javascript"></script>
<!-- Plugin for the DatePicker, full documentation here: https://github.com/uxsolutions/bootstrap-datepicker -->
<script src="../assets/js/plugins/bootstrap-datepicker.js" type="text/javascript"></script>
<!-- Google Maps Plugin -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE"></script>
<!-- Control Center for Now Ui Kit: parallax effects, scripts for the example pages etc -->
<script src="../assets/js/now-ui-kit.js?v=1.3.0" type="text/javascript"></script>
<script src="../assets/js/core/helperFunctions.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.js"></script>
</body>
<script>
$(document).ready(function(){
//var userName = getCookie('myFutureUserName');
var userName = localStorage.getItem('myFutureUserName');
var userID = localStorage.getItem('myFutureUserID');
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('dataKey');
var responseObj = getStudentTopicQuizResult();
/*var responseObj = [
{ "name":"A1", "topic": "A1", "score": "100", "ids": "1009|10" },
{ "name":"A2", "topic": "A1", "score": "100", "ids": "1009|1" }
];
*/
$('#example').dataTable({
"data": responseObj,
"columns": [
{ "data": "name" },
{ "data": "topic" },
{ "data": "score" },
{
"data": "ids",
"render": function(data, type, row, meta){
//if(type === 'display'){
data = '<button type="button" class="btn btn-info btn-sm" onclick="openModal(\'' + data + '\')" >Show Quiz Response</button>';
//}
return data;
}
}
]
});
});
function openModal(quizID) {
alert(quizID);
localStorage.setItem('quizResponseID', quizID);
$("#myModal").modal();
}
</script>
</html>
I Created World Map Using leafletjs And Now Trying To Display Data From https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json As Circle My Data Distribution Output Looks Like
As Of Now Considering Radius As Constant
But It Should Look Like
As Data Is Distributed Across Map
My Codes Are
// load and display the World
d3.json("https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json", function(error, data) {
var map = L.map('map', {
center: [20.0, 5.0],
minZoom: 2,
zoom: 2
});
L.tileLayer('http://{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors | Tiles Courtesy of MapQuest <img src="http://developer.mapquest.com/content/osm/mq_logo.png" width="16" height="16">',
subdomains: ['otile1', 'otile2', 'otile3', 'otile4']
}).addTo(map);
data.features.forEach(function (data2) {
var coordinates = ([+data2.properties.reclong, +data2.properties.reclat]);
var circle = L.circle([coordinates[0],coordinates[1]], 10, {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5
}).addTo(map);
});
});
<!DOCTYPE html>
<html>
<head>
<title>Forced Layout</title>
<meta charset="utf-8" />
<link href="../Content/bootstrap-theme.min.css" rel="stylesheet" />
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<script src="../Scripts/d3/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.6.7/d3-tip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.20/topojson.min.js"></script>
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
<link href="demo.css" rel="stylesheet" />
</head>
<body>
<!--
<div class="mainContainer text-center">
<div id="chart"></div>
</div>
-->
<div id="map" style="height: 440px; border: 1px solid #AAA;"></div>
<script src="../Scripts/jquery-2.2.1.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<script src="demo.js"></script>
</body>
</html>
Fiddle Link
Instead of this
var coordinates = ([+data2.properties.reclong, +data2.properties.reclat]);
it should have been this
var coordinates = ([+data2.properties.reclat, +data2.properties.reclong]);
When you create a circle in leaflet the first array element is lat second is lon. refer
L.circle([50.5, 30.5], 200).addTo(map);
For latlng object lat comes first then lon refer
working code here
I have a basic Ionic App and would like to apply one of three different style sheets based on a User Input.
The page will be pre-loaded with the basic style, then a user can select two other options, so far the original style is loaded and I can console log a change in the variable, but the page is not updated. Here is my code:
HTML INDEX:
<!DOCTYPE html>
<html ng-app="greenwichFitness" ng-controller='SettingsCtrl'>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link ng-href="{{style}}" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-controller='SettingsCtrl'>
<ion-nav-view></ion-nav-view>
<ion-nav-bar class="bar-calm">
<ion-nav-back-button></ion-nav-back-button>
</ion-nav-bar>
</body>
</html>
HTML VIEW:
<div class="list">
<label class="item item-input item-select">
<div class="input-label">
Accessibility Views
</div>
<select ng-model='option' ng-change='changeView(option)'>
<option ng-selected='style'>Plain</option>
<option>Larger Text</option>
<option>Inverted Colours</option>
</select>
</label>
</div>
CONTROLLER:
.controller('SettingsCtrl', function($scope, Settings) {
$scope.style = Settings.style;
$scope.changeView = function(newView) {
Settings.changeView(newView);
};
})
SERVICE:
.factory('Settings', function() {
var defaultStyle = 'lib/ionic/css/ionic.css';
var styles = { 'Plain': defaultStyle,
'Larger Text': 'lib/ionic/css/ionic-large.app.css',
'Inverted Colours': 'lib/ionic/css/ionic-invert.app.css' }
var o = { notifications: false, frequency: 'Daily', style: defaultStyle };
o.changeView = function(newView) {
o.style = styles[newView];
};
)}
Any help would be greatly appreciated.
HTML tag has SettingsCtrl as well BODY tag. Remove one of them.
Also the style seems to be changing only on the factory. style in the scope of SettingsCtrl is not changed. So you can make the changeView return style and assign it to the style variable in the scope.
o.changeView = function(newView) {
o.style = styles[newView];
return o.style
};
And then in controller:
$scope.changeView = function(newView) {
$scope.style = Settings.changeView(newView);
};
Not sure if this is what you had in mind but I got it to work with the following code:
Controller:
$scope.settings = Settings;
HTML:
<link ng-href="{{settings.style}}" rel="stylesheet">
I have a html page with that is to call JSON data from a js file.
The html is below:
<html>
<head>
<meta charset="UTF-8">
<script src="js/angular.js"></script>
<script src="js/angular-route.js"></script>
<script type="text/javascript" src="modules/app.js" ></script>
</script>
<title>
</title>
</head>
<body ng-app="albumsApp">
<div data-ng-controller="albumController">
<ul data-ng-repeat="album in albums">
<li>
{{albums.title}}
</li>
</ul>
</div>
</body>
</html>
The "app.js" file that it calls is below:
**
var albumsApp = angular.module ('albumsApp',[])
albumsApp.factory('albumFactory',function() {
return {
getAlbums: function(){
alert("test");
return [{"artist": "Kid 606","title:":"Happiness"}];
},
};
});
albumsApp.controller ('albumController', function ($scope,albumFactory) {
$scope.albums = albumFactory.getAlbums();
});
**
There are nor errors in the console when I run it, just nothing appears.
The alert box "test" appears when I load the page so the function is getting called, it just doesn't display the JSON. Thank you for any replies.
change this:
{{albums.title}}
to
{{album.title}}
It is OK now, thank you very much.
HTML is
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/angular.js"></script>
<script src="js/angular-route.js"></script>
<script type="text/javascript" src="modules/app.js" ></script>
</script>
<title>
</title>
</head>
<body ng-app="albumsApp">
<div data-ng-controller="albumController">
<ul data-ng-repeat="album in albums">
<li>
Artist is "{{album.artist}} " and title is {{album.title}}
</li>
</ul>
</div>
</body>
</html>
JS is
var albumsApp = angular.module ('albumsApp',[])
albumsApp.factory('albumFactory',function() {
return {
getAlbums: function(){
return [{"artist": "Kid 606","title":"Happiness"}];
},
};
});
albumsApp.controller ('albumController', function ($scope,albumFactory) {
$scope.albums = albumFactory.getAlbums();
});
I have been trying for a while now to figure out how to generate an listview using json in jquery mobile. I have found a lot of examples on the net, but I'm fairly new with json and can't figure out what I am doing wrong?
Here is the page generating the json( test.php):
$matches = array(
array('title' => 'Portugal Open', 'id' => 23),
array('title' => 'Mallorca Invitational', 'id' => 87));
echo $json = json_encode($matches);
And here is how I'm trying to generate the listview:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Mobile Web App</title>
<link href="css/jquery.mobile.theme-1.3.1.css" rel="stylesheet" type="text/css"/>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$(document).ready(function(){
$.getJSON("test.php",function(data) {
$.each(data.posts, function(i,data){
$('#matches').children('ul').append('<li>'+data.title+'</li>');
});
}
);
return false;
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<div data-role="header">
<h1>Page One</h1>
</div>
<div data-role="content" id="matches">
<ul data-role="listview">
</ul>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
</html>
I don't get anything in my listview and I can't figure out why!?
Please help and thanks in advance :-)
Try this code,
$(document).on('pageshow', '#page', function(){
$("#page div:jqmData(role=content) #matches ul").empty();
$.getJSON("test.php",function(data) {
$.each(data.posts, function(i,data){
var html="";
html+="<li><a href='#'>"+data.title+"</a></li>";
$("#page div:jqmData(role=content) #matches ul").append(html);
});
$("#page div:jqmData(role=content) #matches ul:visible").listview("refresh");
});
return false;
});
have fun!!