So I am very confused on how Chrome caches information, my problem is I cannot load in my leaflet map. When I run this code in IIS locally Chrome would cache the old site data and would not update anymore. Then I use ngrok and I clear cache and I have no more map.
At the moment my map is not even loading in locally anymore, I am sure this is very easy and I am missing something please someone explain this to me or point me to a resource to help me. Thanks for any help!
Javascript:
// Create map and get user location
$(document).ready(() => {
createMap()
});
// Map function
const createMap = async () => {
"use strict"
let map = L.map('mapid').setView([51.505, -0.09], 13);
const tileOptions = {
maxZoom: 5,
attribution: '© OpenStreetMap contributors'
}
let OpenStreetMap_Mapnik = await L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', tileOptions).addTo(map);
}
// Update countries list
const getCountry = $.ajax("libs/php/getCountry.php")
getCountry
.done(result => {
if (result.status.name == "ok") {
result["data"].forEach(el => {
$('#countryList').append(new Option(el["name"], el["iso_a2"]));
});
}
})
.catch(err => {
console.log(err)
})
// DOM update
$("#search").click(() => {
console.log($("#countryList").find(":selected").text());
// // GET COUNTRY BORDERS
$.ajax({
url: "libs/php/getCountryBorders.php",
type: 'POST',
dataType: 'json',
data: {
country: $('select').val(),
},
success: function(result) {
// ADD COUNTRY BOUDS
console.log(result["data"]);
},
error: function(err) {console.log(err)}
})
})
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="apple-touch-icon" sizes="180x180" href="source/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="source/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="source/favicon-16x16.png">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin=""/>
<link rel="stylesheet" href="/libs/styles/style.css">
<title>Gazetter</title>
</head>
<body>
<div id="mapid"></div>
<!-- <div class="container-fluid">
<div class="row">
<div class="col-xs-4">
<select name="countryList" id="countryList" class="form-control">
<option value="">Select Country</option>
</select>
<button type="button" name="search" id="search" class="btn btn-info">Search</button>
</div>
<div class="col-xs-8">
<div id="mapid"></div>
</div>
</div>
</div> -->
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="/libs/javascript/script.js"></script>
</body>
</html>
Add a random string or number to end of all URLs that would load some data which doesn't refresh.
Something like this:
const getCountry = $.ajax("libs/php/getCountry.php?rand=" + Math.random())
You have disabled the html with the ids countryList and search and maybe then the js will throw errors in the lines $('#countryList').append(new Option(el["name"], el["iso_a2"]));, console.log($("#countryList").find(":selected").text());, country: $('select').val().
I recommand to test only the clean map without loading data.
Also I never saw await L.tileLayer(' I don't know if this is working correct but test it without await
Related
This project is using the cocktail api to search for a specific ingredient (think gin or vodka) and then return all the drinks that contain the ingredient. I was able to get the results to display, but I wanted the thumbnail pic of the drink (included in the api as strDrinkThumb). When I try to get the pictures to display I get the follow error:
GET http://local/undefined 404 (Not Found)
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
});
let ingredients = document.getElementById('ingredients');
let searchTerm= document.getElementById('search-Bar');
let searchBtn = document.getElementById('searchBtn');
let drinkInfo = document.getElementById('drinkInfo');
let ingredientList = []
searchBtn.addEventListener("click", async (e) => {
const searchString = searchTerm.value.toLowerCase();
fetch(`https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=${searchString}`)
.then((response) => response.json())
.then((filteredIngredients) => {
displayIngredient(filteredIngredients.drinks);
})
.catch((error) => {
});
});
function displayIngredient(drinkData){
const ingredients = [];
//maps over array and makes new array
drinkInfo.innerHTML = drinkData.map( ({strDrink}) => { //destructuring
//use backticks and html
return` <div> //use backticks and html
<div class="card" style="width: 14rem;">
<div class="card-body">
<h5 class="card-title">${strDrink} </h5>
<img src="${drinkData.strDrinkThumb}"/>
</div></div>
`; //use backticks and html
}).join('');
drinkInfo.appendChild(drinkInfo);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cocktail App</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<input type="text" id="search-Bar" placeholder="Enter main ingredient..."/>
<button id="searchBtn">search</button>
</header>
<div class="drinkInfo" id="drinkInfo">
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<script type="text/javascript" src="./extrafile.js"></script>
</body>
</html>
In drinkData.map function you are only pulling strDrink value from the object, you need also get strDrinkThumb
Then you are trying get strDrinkThumb from drinkData which is an array, not an object.
Try this:
drinkInfo.innerHTML = drinkData.map( ({strDrink, strDrinkThumb}) => { //destructuring
//use backticks and html
return` <div> //use backticks and html
<div class="card" style="width: 14rem;">
<div class="card-body">
<h5 class="card-title">${strDrink} </h5>
<img src="${strDrinkThumb}"/>
</div></div>
`; //use backticks and html
}).join('');
I'm trying to get a regular form field used for searching for an address to autocomplete its values, as seen on this page, using Leaflet Geosearch plugin.
So far the documentation says it can be binded to a form. Jquery UI's autocomplete looks like it can accomplish this, however i have not been able to wrap my head around how to do it.
I have successfully linked the form field to the geosearch provider, and it returns an array that can be seen in the browser console. I can algo get the autocomplete plugin to work, but with a local array, not the one produced by the geosearch plugin.
Here is an example of both plugins in action separately:
<!DOCTYPE html>
<html>
<head>
<title>Leaflet tests</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"></script>
<style type="text/css"> #mapid { height: 500px; width: 500px}</style>
<link rel="stylesheet" href="https://unpkg.com/leaflet-geosearch#3.0.0/dist/geosearch.css" />
<script src="https://unpkg.com/leaflet-geosearch#3.0.0/dist/geosearch.umd.js"></script>
</head>
<body>
<div id="mapid"></div>
<hr>
<div class="">
<label for="search">geosearch field (check console): </label>
<input id="search">
</div>
<div class="">
<label for="search2">autocomplete field (apple or banana): </label>
<input id="search2">
</div>
<script type="text/javascript">
//code for generating map below
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap',
subdomains: ['a','b','c']
}).addTo(mymap);
//code for search form below
const providerform = new GeoSearch.OpenStreetMapProvider();
const input = document.querySelector('input[id="search"]');
input.addEventListener('input', async (event) => {
const results = await providerform.search({ query: input.value });
console.log(results[0]); // » [{}, {}, {}, ...]
});
//
let fruits = ['Apple', 'Banana']
$("#search2").autocomplete(
{
source: fruits,
delay: 100,
minLength: 1
});
</script>
</body>
</html>
I'd greatly appreciate any pointers in the right direction on how to get the autocomplete to work with the geosearch provider.
This should work, but I don't know how to check at the moment because https://nominatim.openstreetmap.org/ is currently not working.
$('#search2').autocomplete({
source(request, response) {
const providerform = new GeoSearch.OpenStreetMapProvider({
params: {
limit: 5
}
});
return providerform.search({ query: request.term }).then(function (results) {
response(results);
});
},
delay: 100,
minLength: 1
});
Here's one basic example using jquery, there are other options too
const input = document.querySelector('input[id="search2"]');
input.addEventListener('input', async (event) => {
const results = await providerform.search({ query: input.value });
console.log(results[0]); // » [{}, {}, {}, ...]
});
let fruits = ['Apple', 'Banana']
$("#search2").autocomplete(
{
source: fruits,
delay: 100,
minLength: 1
});
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="//code.jquery.com/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<hr>
<h1> Autocomplerde demo </h1>
<div class="">
<label for="search2">autocomplete field (apple or banana): </label>
<input id="search2">
</div>
<script type="text/javascript">
</script>
</body>
</html>
Can anyone help in resolving this issue?, I am trying to create a map showing map markers of power plants in the US and also a heatmap later on. The problem with my code is that my map is not even showing when it goes live. I have attached the config, location and index files to help with finding the issue. I initially had a local csv file, which I converted to geojson which was then deployed on github.
config.js
// API key
const API_KEY = "pk.eyJ1IjoidGF1cmVhbmgiLCJhIjoiY2tmb21yc2tzMDFnYTJ0bXVuMzVub2tvYyJ9.vhUstehmvTj6HgfalepX8w";
location.js
var myMap = L.map("map", {
center: [37.7749, -122.4194],
zoom: 13
});
// Adding tile layer
L.tileLayer("https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}", {
attribution: "© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong><a href='https://www.mapbox.com/map-feedback/' target='_blank'>Improve this map</a></strong>",
tileSize: 512,
maxZoom: 18,
zoomOffset: -1,
id: "mapbox/streets-v11",
accessToken: API_KEY
}).addTo(myMap);
var url = "https://taureanh.github.io/geojson/";
d3.json(url, function(response) {
console.log(response);
for (var i = 0; i < response.length; i++) {
var geometry = response[i].geometry;
if (geometry) {
L.marker([geomtery.coordinates[1], geometry.coordinates[0]]).addTo(myMap);
}
}
});
index.html
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Map Markers</title>
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.3/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<!-- Our CSS -->
<link rel="stylesheet" href="./static/css/style.css" />
</head>
<body>
<div id="map"></div>
<!-- API key -->
<script type="text/javascript" src="static/js/config.js"></script>
<!-- Leaflet JS -->
<script src="https://unpkg.com/leaflet#1.3.3/dist/leaflet.js" integrity="sha512-tAGcCfR4Sc5ZP5ZoVz0quoZDYX5aCtEm/eu1KhSLj2c9eFrylXZknQYmxUssFaVJKvvc0dJQixhGjG2yXWiV9Q==" crossorigin=""></script>
<!-- D3 CDN -->
<script src="https://d3js.org/d3.v4.min.js"></script>
<!-- JS -->
<script type="text/javascript" src="static/js/location.js"></script>
<!-- <script type="text/javascript" src="static/js/heatmap.js"></script> -->
<!-- Leaflet heatmap plugin-->
<script type="text/javascript" src="static/js/leaflet-heat.js"></script>
</body>
</html>
d3.json expects JSON, but your endpoint is returning HTML:
curl -I https://taureanh.github.io/geojson/
HTTP/2 200
server: GitHub.com
content-type: text/html; charset=utf-8
You should update your endpoint so that is actually returns JSON: content-type: application/json; just data, no <html> tags.
Alternatively, you could update location.js to get the endpoint (d3.request(url, function(html)), then parse the response into JSON yourself (strip the html tags, then use JSON.parse). This will work, but it's messy and not ideal.
Hay I have a problem with sorting divs from createElement function.
Problem:
I create divs from database-items which are align in row (latest item on the end)
What I want:
Display the Items in reversed direction. The latest item added to the database should appear as first item in the stream (like a newsstream on facebook).
Question:
How can I change just the direction the divs are loaded/created?
Further I thought about a technique to set an individual ID to each div created, for sorting them later by ID (Id could be ongoing numbers).
I found this one but it don´t works while i does not increment the ID-number: Javascript create divs with different ids
I know there are many Questions like this on stackoverflow, and I tried several before, with no success for my issue.
Check out my Code:
//create firebase reference
var dbRef = new Firebase("….com/");
var contactsRef = dbRef.child('contacts')
//load all contacts
contactsRef.on("child_added", function(snap) {
//console.log(snap.val())
snap.forEach(function(childSnapshot) {
var key = childSnapshot.key();
var childData = childSnapshot.val();
var divCount = 0;
//create divs from database-elements
var card = document.createElement('div');
card.id = 'div'+divCount;
card.setAttribute('class', 'linkprev');
document.body.appendChild(card);
var cardtitle = document.createElement('div');
cardtitle.setAttribute('class', 'cardtitle');
cardtitle.innerHTML = childData;
card.appendChild(cardtitle);
document.guteUrls.execute();
divCount++;
console.log(event);
//linkify plugin to convert div-elements (strings) to hyperlinks
$('div').linkify();
$('#sidebar').linkify({
target: "_blank"
});
});
});
//save contact
document.querySelector(".addValue").addEventListener("click", function( event ) {
event.preventDefault();
if( document.querySelector('#url').value != '' && document.querySelector('#url').value.charAt(0) == "h" && document.querySelector('#url').value.charAt(3) == "p"){
contactsRef.push({
name: document.querySelector('#url').value,})
contactForm.reset();}
else {
alert('Oops, seems like an error…');
}
}, false);
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>frontendpublishing-test</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="http://cdn.embed.ly/jquery.preview-0.3.2.css" />
<link href="css/flexboxgrid.min.css" rel="stylesheet">
<style type="text/css">
#contacts p,
#contacts p.lead{
margin: 0;
}
</style>
</head>
<body>
<div class="container">
<h1>Titel h1</h1>
<hr/>
<div class="row">
<div class="col-md-6">
<form method="post" name="contactForm">
<div class="form-group">
<input id="url" type="url" required name="url" placeholder="share a good article/blog/topic" class="input">
<button type="submit" class="btn btn-primary addValue">Submit</button>
</form>
<!-- <script>
$document.ready(function){
document.getElementsByClassName('linkified');
{console.log("linkified")};
};
</script>
-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Latest compiled and minified Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<!-- Include Firebase Library -->
<script src="https://cdn.firebase.com/js/client/2.2.3/firebase.js"></script>
<!-- Contacts Store JavaScript -->
<script src="script.js"></script>
<script src="linkify.min.js"></script>
<script src="linkify-jquery.min.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script async src="https://guteurls.de/guteurls.js"
selector='.linkprev'
gif="http://loading.io/assets/img/default-loader.gif"
callback-a="(function(jqueryElement,url,$){console.log('url:'+url)})"
callback="(function($){console.log('finished')})"
init="(function($){console.log('JS will start to search URLs now')})"
></script>
</body>
</html>
Thanks for helping :)
since you are using jquery instead of
document.body.appendChild(card);
use
$('body').prepend($(card))
you can mark up the area with an id you want to add them into so that it does not insert into the top of your document like
$('#elementid').prepend($(card))
1.Why not query them descendent from db? :))
2.
card.childNodes.length
? card.insertBefore(cardtitle, card.childNodes[0])
: card.appenChild(cardtitle);
I am learning angular js right now and have hit another rut. I am trying to make my buttons change the movie ID. I know it is recognizing the click because I had it change some words in the HTML file to test it. I think it isn't talking to my JS file.
I found this during my search http://jsfiddle.net/7Sg6a/. The docs just have an expression inside the parenthesis and this example has parameters. I tried both and a few other but neither worked.
Here is my latest failed attempt. If I could get a nudge in the right direction I would be very grateful.
<!DOCTYPE HTML>
<html lang = "en" ng-app="movies"><!-- lets page use controllers/movies.js-->
<head>
<title>Watch a movie!</title>
<meta charset = "UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="http://www.mysite.com/rss/rss2.xml" />
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/style.css" rel="stylesheet" type="text/css">
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">
<!-- <link href="css/bootstrap-responsive.min.css" rel="stylesheet" type="text/css"> -->
<!-- Preloading scripts? -->
<script src="js/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.0rc1/angular-route.min.js"></script>
<!--<script src="js/angular-resource.min.js" type="text/javascript"></script>-->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- <script src="js/bootstrap.js"></script> -->
<script src="controllers/movies.js"></script>
</head>
<body>
<div id="wrapper">
<header>
<div id="logo">
<img src="images/logo.png" alt="Cinema Plus - Movies plus a whole lot more." class="img-responsive">
</div>
</header>
<nav>
<div class='row-fluid'>
<div class="span2"></div>
<button ng-click="nowShowing()" type="button" class="btn btn-primary btn-lg span4 "><h3>NOW PLAYING</h3></button>
<button ng-click="comingSoon()" type="button" class="btn btn-default btn-lg span4 "><h3>COMING FRIDAY</h3></button>
<div class="span2"></div>
</div>
</nav>
<div id='content' class='row-fluid'>
<div class='span8 info'>
<h2 ng-controller = "movieController">{{movies.title}}</h2>
<h2 ng-controller = "movieController">RATED: {{movies.mpaa_rating}}</h2>
<h2 ng-controller = "movieController">{{movies.runtime}} Minutes</h2>
<p ng-controller = "movieController">DESCRIPTION: {{movies.synopsis}}</p>
</div>
<div class='span4 poster'>
<img ng-controller = "movieController" src={{movies.posters.original}} alt={{movies.title}} class="img-responsive">
</div>
</div>
<div>
Note: This theator only plays one movie at a time. film will be hard coded into the app. Would like to see it fed by RSS orsomething in the future.
</div>
</div> <!-- END WRAPPER -->
</body>
</html>
JS
var movies = angular.module('movies', []);
movies.controller('movieController', function ($scope, $http) {
$http.jsonp('http://api.rottentomatoes.com/api/public/v1.0/movies/771303861.json', {
params: {
apikey: 'wq98h8vn4nfnuc3rt2293vru',
callback: 'JSON_CALLBACK'
}
})
.success(function (data) {
$scope.movies = data;
});
});
movies.click('nowShowing', function ($scope){
alert("asdasd");
});
how long until I actually get this and can stop asking stupid questions?
your .click function doesn't belong. You're using Angular like jQuery, and it's more (awesome) than that. You need to put the nowShowing function and such inside your controller:
var movies = angular.module('movies', []);
movies.controller('movieController', function ($scope, $http) {
$http.jsonp('http://api.rottentomatoes.com/api/public/v1.0/movies/771303861.json', {
params: {
apikey: 'secret',
callback: 'JSON_CALLBACK'
}
})
.success(function (data) {
$scope.movies = data;
});
$scope.nowShowing = function(){
//whatever is in here will execute when a user interacts with an element with the ng-click="" directive
}
});
Also, I would highly recommend you create a service for your http requests to your api. You are creating a tightly coupled app with your current approach.
movies.factory('moviedata',function($http){
return
$http.jsonp('http://api.rottentomatoes.com/api/public/v1.0/movies/771303861.json', {
params: {
apikey: 'secret',
callback: 'JSON_CALLBACK'
}
})
})
then 'inject' it in your controller like so:
movies.controller('movieCtrl',function($scope, moviedata){
//resolve returned promise
moviedata.success(function(data){
$scope.data = data;
});
$scope.nowShowing = function($log){
//whatever is in here will execute when a user interacts with an element with the ng-click="" directive
$log.info("nowShowing method fired");
}
})