Mapbox + jsFiddle + Wordpress - javascript

I apologize in advance for my very limited knowledge of coding. I've been trying to add a custom search bar linked to Mapbox on my Wordpress site without any luck. I created, or actually I edited a jsFiddle that I found. Where I'm having trouble is adding the Javascript from jsFiddle to Wordpress...
Here's the working jsFiddle: https://jsfiddle.net/erinlink/4q9brvkt/16/
L.mapbox.accessToken = 'pk.eyJ1IjoiZXJpbmxpbmsiLCJhIjoiWnpiWXQ5RSJ9.hy5rpmPf-gpFRaNG7GHfAA';
var geocoder = L.mapbox.geocoder('mapbox.places'),
map = null;
var map = L.mapbox.map('mapbox', 'erinlink.bee96628').setView([30.267153, -97.74306079999997], 12);
var featureLayer = L.mapbox.featureLayer('erinlink.bee96628')
.addTo(map);
/*
var featureLayer = L.mapbox.featureLayer()
.addTo(map);
featureLayer.loadID('your_id');
*/
// both versions to add the featurelayer work
function showMap(err, data) {
// The geocoder can return an area, like a city, or a
// point, like an address. Here we handle both cases,
// by fitting the map bounds to an area or zooming to a point.
if (!map) {
map = L.mapbox.map('mapbox', 'erinlink.bee96628');
}
if (data.lbounds) {
map.fitBounds(data.lbounds);
} else if (data.latlng) {
map.setView([data.latlng[0], data.latlng[1]], 12);
}
}
function geocodeThis() {
var text = document.getElementById('searchMap').value;
if (text.length >= 5) {
geocoder.query(text, showMap);
}
}
body {
margin: 0;
padding: 0;
}
#mapbox {
width: 100%;
height: 100%;
border: 0px solid transparent;
}
#searchMap {
z-index: 10000 !important;
position: relative;
float: right;
text-overflow: ellipsis;
padding: 2px 0px 2px 6px;
background-color: #fff;
color: gray;
font-size: 12pt;
font-family: Trebuchet MS;
height: 24px;
width: 200px;
border: 0px solid transparent;
border-radius: 4px 4px 4px 4px;
margin: 0px 120px 10px 10px;
}
.mapbox_header {
color: white;
text-align: right;
font-size: 10pt;
font-family: Trebuchet MS;
font-style: italic;
font-weight: 100;
margin: 10px 120px 10px 0;
}
<link href="https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.css" rel="stylesheet" />
<script src="https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.js"></script>
<div style="margin-top:1px; padding: 4px 40px 0px 0px; background: #77bc1f; width:100%; height:10%;">
<div>
<ul>
<input type='text' oninput='geocodeThis()' id='searchMap' placeholder='Enter address or zip'>
<br>
<br>
<p class="mapbox_header">Looking for a particular flavor or bottle size in your area? Contact us for more info.</p>
</ul>
</div>
</div>
<div>
<div id='mapbox' style="height:400px; width:100%;"></div>
</div>
Here's the page I've been trying to get it working on (the current
map on this page is not linked to the search bar):
http://yellowbirdsauce.com/locations/
Thanks in advance for any help!!

Related

A Notepad that keep the notes written even after refresh

I have just found a set of codes that fits my need right now for my blog.
Here I'll attach the code and a glimpse of what it looks like. Although It's still very simple.
What I want to ask is if it's possible to tweak these code possible using JS localstorage, so that it will keep all the saved text even after the user refresh the page, or even better if it stays there even after a user closed the window and reopened it later?
Here's what it looks like right now
and here is the code:
$(document).ready(function(){
var noteCount = 0;
var activeNote = null;
$('.color-box').click(function(){
var color = $(this).css('background-color');
$('notepad').css('background-color', color);
$('#title-field').css('background-color', color);
$('#body-field').css('background-color', color);
})
$('#btn-save').click(function(){
var title = $('#title-field').val();
var body = $('#body-field').val();
if (title === '' && body === '') {
alert ('Please add a title or body to your note.');
return;
}
var created = new Date();
var color = $('notepad').css('background-color');
var id = noteCount + 1;
if (activeNote) {
$('#' + activeNote)[0].children[0].innerHTML = title;
$('#' + activeNote)[0].children[1].innerHTML = created.toLocaleString("en-US");
$('#' + activeNote)[0].children[2].innerHTML = body;
$('#' + activeNote)[0].style.backgroundColor = color;
activeNote = null;
$('#edit-mode').removeClass('display').addClass('no-display');
} else {
var created = new Date();
$('#listed').append('<div id="note' + id + '" style="background-color: ' + color + '"><div class="list-title">' + title + '</div> <div class="list-date">' + created.toLocaleString("en-US") + '</div> <div class="list-text">' + body + '</div> </div>');
noteCount++;
};
$('#title-field').val('');
$('#body-field').val('');
$('notepad').css('background-color', 'white');
$('#title-field').css('background-color', 'white');
$('#body-field').css('background-color', 'white');
});
$('#btn-delete').click(function(){
if (activeNote) {
$('#' + activeNote)[0].remove();
activeNote = null;
$('#edit-mode').removeClass('display').addClass('no-display');
}
$('#title-field').val('');
$('#body-field').val('');
$('notepad').css('background-color', 'white');
$('#title-field').css('background-color', 'white');
$('#body-field').css('background-color', 'white');
});
$('#listed').click(function(e){
var id = e.target.parentElement.id;
var color = e.target.parentElement.style.backgroundColor;
activeNote = id;
$('#edit-mode').removeClass('no-display').addClass('display');
var titleSel = $('#' + id)[0].children[0].innerHTML;
var bodySel = $('#' + id)[0].children[2].innerHTML;
$('#title-field').val(titleSel);
$('#body-field').val(bodySel);
$('notepad').css('background-color', color);
$('#title-field').css('background-color', color);
$('#body-field').css('background-color', color);
})
})
header {
text-align: left;
font-weight: 800;
font-size: 28px;
border-bottom: solid 3px #DEDEDE;
display: flex;
justify-content: space-between;
}
footer {
display: flex;
flex-flow: row-reverse;
padding: 5px 20px;
}
.headers {
margin-top: 20px;
margin-bottom: -10px;
font-size: 20px;
}
#list-head {
margin-left: 2.5%;
width: 30.5%;
display: inline-block;
text-align: center;
}
#note-head {
width: 60%;
margin-left: 5%;
display: inline-block;
text-align: center;
}
noteList {
margin-top: 20px;
display: inline-block;
margin-left: 2.5%;
width: 30.5%;
height: 400px;
overflow: scroll;
border: solid 3px #929292;
border-radius: 5px;
background-color: #DEDEDE;
}
.within-list {
cursor: pointer;
}
.list-title {
font-weight: 600;
font-size: 20px;
padding: 5px 5px 0 5px;
}
.list-date {
font-weight: 200;
font-style: italic;
font-size: 12px;
padding: 0 5px 0 5px;
}
.list-text {
padding: 0 5px 5px 5px;
border-bottom: solid 1px black;
}
notePad {
display: inline-block;
border: solid 3px black;
border-radius: 10px;
height: 400px;
overflow: scroll;
width: 60%;
margin-left: 5%;
margin-top: 0;
}
#note-title {
font-size: 24px;
padding: 0 0 5px 5px;
border-bottom: solid 2px #DEDEDE;
}
#note-body {
padding: 5px;
}
#body-field, #title-field {
width: 100%;
border: none;
outline: none;
resize: none;
}
#title-field {
font-size: 18px;
font-weight: 600;
}
#body-field {
font-size: 14px;
font-weight: 500;
height: 400px;
}
#color-select {
display: flex;
flex-flow: row-reverse nowrap;
padding: 5px 10px 0 0;
}
.color-box {
border: solid 2px #929292;
height: 10px;
width: 10px;
margin-left: 5px;
}
.display {
display: visible;
}
.no-display {
display: none;
}
button {
margin: 5px;
border: solid 3px grey;
border-radius: 10%;
font-size: 22px;
font-weight: 800;
text-transform: uppercase;
color: #DEDEDE;
}
button:hover, .color-box:hover {
cursor: pointer;
}
#listed:nth-child(odd):hover {
cursor: pointer;
}
#btn-save {
background-color: #2F5032;
}
#btn-delete {
background-color: #E41A36;
}
.white {
background-color: white;
}
.orange {
background-color: #FFD37F;
}
.banana {
background-color: #FFFA81;
}
.honeydew {
background-color: #D5FA80;
}
.flora {
background-color: #78F87F;
}
.aqua {
background-color: #79FBD6;
}
.ice {
background-color: #79FDFE;
}
.sky {
background-color: #7AD6FD;
}
.orchid {
background-color: #7B84FC;
}
.lavendar {
background-color: #D687FC;
}
.pink {
background-color: #FF89FD;
}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title></title>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
The Note Machine
<div id='color-select'>
<div class='color-box white'></div>
<div class='color-box orange'></div>
<div class='color-box banana'></div>
<div class='color-box honeydew'></div>
<div class='color-box flora'></div>
<div class='color-box aqua'></div>
<div class='color-box ice'></div>
<div class='color-box sky'></div>
<div class='color-box orchid'></div>
<div class='color-box lavendar'></div>
<div class='color-box pink'></div>
</div>
</header>
<main>
<div class="headers">
<div id="list-head">
<b>Your Notes</b> <i>(click to edit/delete)</i>
</div>
<div id="note-head">
<b>Your Notepad</b>
<span id="edit-mode" class="no-display">
<i> (edit mode) </i>
</span>
</div>
</div>
<noteList>
<div id='listed'>
</div>
</noteList>
<notepad>
<div id="note-title">
<input id="title-field" type="text" placeholder="title your note">
</div>
<div id="note-body">
<textarea id="body-field"></textarea>
</div>
</notepad>
</main>
<footer>
<button id="btn-save">Save</button>
<button id="btn-delete">Delete / Clear </button>
</footer>
</body>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'></script>
<script type='text/javascript' src='app.js'></script>
</html>
I tried searching in the net for other notepads, but they aren't working on my blog, and here's the one that is finally working. I would really appreciate any kind of suggestions and assistance. T
If all you want to do is save to LocalStorage when save is clicked, then it would be as simple as saving the title and body variables to LocalStorage in the $('#btn-save').click() handler.
Assuming that (as #Nawed Khan guessed) you want to have the note saved without the user having to click save, then you'll want to make three changes:
In the main body of your $(document).ready() function, check for existing LocalStorage values, and if they exist, then set them on your $('#title-field') and $('#body-field') elements.
Add two new change handlers to your $('#title-field') and $('#body-field') elements. When these change handlers fire, get the title and body values from the elements and save them to LocalStorage.
In the $('#btn-save').click() and $('#btn-delete').click() handlers, reset the LocalStorage values of the active note.
You should find these links useful:
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
https://api.jquery.com/change/
P.S. The information stored in LocalStorage can be lost if the user chooses to clear their browser data. If preservation of the data is vital, then implementing a solution using AJAX to connect to a database as #The Rahul Jha suggested would guarantee preservation of the data.
Yes , You can save the data in localStorage and fetch the data on page load. To set the localStorage item add below function in your script which is setting the item on keyup of textarea in localstorage.
$(document).on("keyup","#body-field",function(){
var text = $("#body-field").val();
localStorage.setItem("savedData", text);
});
Add below method to fetch the data from local storage
function loadDataFromLocalStorage(){
if (localStorage.getItem("savedData") !== null) {
$("#body-field").val(localStorage.getItem("savedData"))
}
}
And at last call the above method in $(document).ready() or page load to set the data back in text area after page load.
Put this inside the $(document).ready block:
$(“#title-field”).val(window.localStorage.getItem(“title”) || “”);
$(“#body-field”).val(window.localStorage.getItem(“body”) || “”);
$(“#title-field, #body-field”).change(function() {
var title = $(“#title-field”).val();
var body = $(“#body-field”).val();
window.localStorage.setItem(“title”, title);
window.localStorage.setItem(“body”, body)
})
The 2 first lines will load the text from the localStorage and sets the data on the corresponding inputs
The rest of the code is the part where the data is being saved to localStorage every time the value of #title-field OR #body-field changes.

Wondering why my javascript file isn't loading when I run phonegap?

Let me know if I have to post this a different way, but I uploaded the three files I am working with. I am pretty new to jQuery and javascript but in my class I am supposed to be able to get this combination of files running and what is supposed to be happening when I run this HTML file is that when I hit "Submit" on the bottom of the form without entering anything into the text areas, it should return an error message and a little exclamation mark.
Currently, it isn't returning anything at all. The .css file loads fine and changes my form to look like what it is supposed to, but not the .js file. I am wondering if it has something to do with the script tags in the head section of the html file?
For context, I did write most of this myself from the book instructions but apparently the school provided the completed code in separate files which was formatted much cleaner than mine, so I just replaced mine with what you see here. The main section that wasn't clarified on either in the book or by my professor (good luck, he doesn't answer emails) is the information to load Jquery/javascript files in the header section. I am using phoneGap to emulate this web page.
var errors = {};
function displayErrors() {
// initialise variables
var haveErrors = false;
// remove the invalid class for all inputs
$(":input.invalid").removeClass("invalid");
// iterate through the fields specified in the errors array
for (var fieldName in errors) {
haveErrors = true;
$("input[name='" + fieldName + "']").addClass("invalid");
} // for
// if we have errors, then add a message to the errors div
$("#errors")
.html(haveErrors ? "Errors were found." : "")
.css("display", haveErrors ? "block" : "none");
} // displayErrors
function displayFieldErrors(field) {
var messages = errors[field.name];
if (messages && (messages.length > 0)) {
// find an existing error detail section for the field
var errorDetail = $("#errordetail_" + field.id).get(0);
// if it doesn't exist, then create it
if (! errorDetail) {
$(field).before("<ul class='errors-inline' id='errordetail_" + field.id + "'></ul>");
errorDetail = $("#errordetail_" + field.id).get(0);
} // if
// add the various error messages to the div
for (var ii = 0; ii < messages.length; ii++) {
$(errorDetail).html('').append("<li>" + messages[ii] + "</li>");
} // for
} // if
} // displayFieldErrors
$(document).ready(function() {
$(":input").focus(function(evt) {
displayFieldErrors(this);
}).blur(function(evt) {
$("#errordetail_" + this.id).remove();
});
$("#taskentry").validate({
submitHandler: function(form) {
// TO BE COMPLETED IN THE NEXT CHAPTER
},
showErrors: function(errorMap, errorList) {
// initialise an empty errors map
errors = {};
// iterate through the jQuery validation error map, and convert to
// something we can use
for (var elementName in errorMap) {
if (! errors[elementName]) {
errors[elementName] = [];
} // if
errors[elementName].push(errorMap[elementName]);
} // for
// now display the errors
displayErrors();
}
});
});
body {
margin: 0px;
min-height: 480px;
font-family: Arial;
}
form ul {
margin: 0px;
padding: 6px;
list-style-type: none;
}
form ul li {
margin: 0 0 4px 0;
-webkit-border-radius: 4px;
border: 1px solid #666666;
padding: 4px;
}
form ul li.naked {
-webkit-border-radius: 0px;
border: 0;
padding: 0;
}
input, textarea {
-webkit-appearance: none;
border: 0;
width: 99%;
}
input.invalid, textarea.invalid {
background: url(exclamation.png) no-repeat 2px 2px;
padding-left: 22px;
}
#errors {
margin: 8px 6px 2px 6px;
padding: 6px 14px;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.0, #cc0000), color-stop(0.7, #770022));
-webkit-border-radius: 4px;
color: white;
display: none;
}
ul.errors-inline li {
border: 0px;
color: red;
padding: 0px;
}
input[type=submit] {
border: 1px solid white;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.0, #F8F8F8), color-stop(1.0, #AAAAAA));
-webkit-border-radius: 6px;
-webkit-box-shadow: 0 0 4px #333333;
width: 100%;
padding: 6px;
}
h1.simple {
font-size: 0.9em;
padding: 8px 4px 4px 8px;
background: #333333;
color: #AAAAAA;
border-bottom: 2px solid #AAAAAA;
margin: 0 0 4px 0;
}
h1.fancy {
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.0, #666666), color-stop(0.5, #3A3A3A), color-stop(0.5, #222222), color-stop(1.0, #000000));
-webkit-box-shadow: 0 2px 1px #AAAAAA;
-webkit-border-bottom-left-radius: 6px;
-webkit-border-bottom-right-radius: 6px;
font-size: 1.1em;
color: white;
padding: 10px 8px;
margin: 0 6px 6px 6px;
text-align: center;
}
<html>
<head>
<title>Simple Mobile Web Page</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
<link rel="stylesheet" media="screen" href="todolist.css" />
<script type="text/javascript" src="../../js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../../js/jquery.validate.js"></script>
<script type="text/javascript" src="todolist.js"></script>
</head>
<body>
<h1 class="fancy">Christopher Hughes To Do List</h1>
Hello World!
<p>
This is just the beginning!
</p>
<span class="highlight">
More to come!
</span>
<h1 class="fancy">Create Task</h1>
<div id="errors"></div>
<form id="taskentry">
<ul>
<li><input type="text" name="task[name]" id="taskname" placeholder="Task Name"/></li>
<li>
<textarea name="task[description]" id="taskdesc" placeholder="Description" rows="5"></textarea>
</li>
<li><input type="text" name="task[due]" id="taskdue" placeholder="Task Due" /></li>
<li class="naked"><input type="submit" name="Save" /></li>
</ul>
</form>
</body>
</html>

infoWindow in google maps on multiple markers [duplicate]

This question already has answers here:
Google Maps JS API v3 - Simple Multiple Marker Example
(15 answers)
Closed 6 years ago.
i've created a google maps, which retrieve data from a csv file. This seem to work fine, however when i loop through all the objects the infoWindow does not seem to work. i guess this is due to the fact that the marker variable is inside a for loop. i've tried to move the code to inside the loop, however this result in the infoWindow placed randomly on the map instead above the clicked marker. How can i achieve the infoWindow to work with multiple markers?
db.csv example
40.740;-74.18;test;haha;
40.740;-74.20;test;haha;
html & java
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="normalize.css">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
<div id="mapContainer">
<div id="map"></div>
</div>
<div id="abc">
<div id="popupContact">
<section class="register">
<h1>CAMP INFORMATIONER:</h1>
<form method="post" action="index.html">
<div class="reg_section personal_info">
<input type="text" name="username" value="" placeholder="Campnavn">
<textarea name="textarea" id="description" placeholder="Beskrivelse"></textarea>
</div>
<div>
<span class="submit" style="text-align: left; padding: 0 10px;"><input TYPE="button"name="commit" value="Tilføj" onclick="placeMarker(currentMarker, document.getElementById('description'));"></span>
<span class="submit" style="text-align: right; padding: 0 10px;"><input TYPE="button" name="commit" value="Fortryd" onclick="div_hide();"></span>
</div>
</form>
</section>
</div>
</div>
</div>
<script>
var mapCanvas;
var currentMarker;
function initialize() {
var myOptions = {
center: {lat: 40.740, lng: -74.18},
zoom : 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapCanvas = new google.maps.Map(document.getElementById("mapContainer"), myOptions);
var returnValue = "";
var request = new XMLHttpRequest();
// Read the lat/long info for markers
request.open("GET", "db.csv", false);
request.send(null);
returnValue = request.responseText;
// Convert our data from the CVS file to a usable array
var data = CSVToArray(returnValue);
for (var i = 0; i < data.length; i++)
{
// Create a lat/long object readable by Google
var myLatlng = new google.maps.LatLng(parseFloat(data[i][0]), parseFloat(data[i][1]));
// Generate a marker from the lat/long object and add it to the map
var marker = new google.maps.Marker({
position: myLatlng,
map: mapCanvas,
title: data[i][2],
description: data[i][3]
});
}
var imageBounds = {
north: 40.773941,
south: 40.712216,
east: -74.12544,
west: -74.22655
};
historicalOverlay = new google.maps.GroundOverlay(
'http://i.stack.imgur.com/0mgx2.jpg',
imageBounds);
historicalOverlay.setMap(mapCanvas);
// This event listener calls addMarker() when the map is clicked.
google.maps.event.addListener(historicalOverlay, 'click', function(e) {
console.log("clicked'");
currentMarker = e.latLng;
infowindow.close();
div_show();
});
//Changes zoom levels when the projection is available.
google.maps.event.addListenerOnce(mapCanvas, "projection_changed", function(){
mapCanvas.setMapTypeId(google.maps.MapTypeId.HYBRID); //Changes the MapTypeId in short time.
setZoomLimit(mapCanvas, google.maps.MapTypeId.ROADMAP);
setZoomLimit(mapCanvas, google.maps.MapTypeId.HYBRID);
setZoomLimit(mapCanvas, google.maps.MapTypeId.SATELLITE);
setZoomLimit(mapCanvas, google.maps.MapTypeId.TERRAIN);
mapCanvas.setMapTypeId(google.maps.MapTypeId.ROADMAP); //Sets the MapTypeId to original.
});
// InfoWindow content
var content = '<div id="iw-container">' +
'<div class="iw-title">title</div>' +
'<div class="iw-content">' +
'<p>Founded in 1824, the Porcelain Factory of Vista Alegre was the first industrial unit dedicated to porcelain production in Portugal. For the foundation and success of this risky industrial development was crucial the spirit of persistence of its founder, José Ferreira Pinto Basto. Leading figure in Portuguese society of the nineteenth century farm owner, daring dealer, wisely incorporated the liberal ideas of the century, having become "the first example of free enterprise" in Portugal.</p>' +
'</div>' +
'<div class="iw-bottom-gradient"></div>' +
'</div>';
// A new Info Window is created and set content
var infowindow = new google.maps.InfoWindow({
content: content,
// Assign a maximum value for the width of the infowindow allows
// greater control over the various content elements
maxWidth: 350
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(mapCanvas, marker);
//title
document.getElementById("iw-title").innerHTML = marker.title;
//description
document.getElementById("iw-content p").innerHTML = marker.description;
});
// Event that closes the Info Window with a click on the map
google.maps.event.addListener(mapCanvas, 'click', function() {
infowindow.close();
});
google.maps.event.addListener(infowindow, 'domready', function() {
// Reference to the DIV that wraps the bottom of infowindow
var iwOuter = $('.gm-style-iw');
/* Since this div is in a position prior to .gm-div style-iw.
* We use jQuery and create a iwBackground variable,
* and took advantage of the existing reference .gm-style-iw for the previous div with .prev().
*/
var iwBackground = iwOuter.prev();
// Removes background shadow DIV
iwBackground.children(':nth-child(2)').css({'display' : 'none'});
// Removes white background DIV
iwBackground.children(':nth-child(4)').css({'display' : 'none'});
// Moves the infowindow 115px to the right.
iwOuter.parent().parent().css({left: '115px'});
// Moves the shadow of the arrow 76px to the left margin.
iwBackground.children(':nth-child(1)').attr('style', function(i,s){ return s + 'left: 76px !important;'});
// Moves the arrow 76px to the left margin.
iwBackground.children(':nth-child(3)').attr('style', function(i,s){ return s + 'left: 76px !important;'});
// Changes the desired tail shadow color.
iwBackground.children(':nth-child(3)').find('div').children().css({'z-index' : '1'});
// Reference to the div that groups the close button elements.
var iwCloseBtn = iwOuter.next();
// Apply the desired effect to the close button
iwCloseBtn.css({opacity: '1', right: '38px', top: '3px', border: '7px solid #fff', 'border-radius': '13px', 'box-shadow': '0 0 5px #7D0F33'});
// If the content of infowindow not exceed the set maximum height, then the gradient is removed.
if($('.iw-content').height() < 140){
$('.iw-bottom-gradient').css({display: 'none'});
}
// The API automatically applies 0.7 opacity to the button after the mouseout event. This function reverses this event to the desired value.
iwCloseBtn.mouseout(function(){
$(this).css({opacity: '1'});
});
});
}
function div_show() {
$('#abc').fadeIn(400);
}
//Function to Hide Popup
function div_hide(){
$('#abc').fadeOut(400);
}
function placeMarker(location, label) {
var marker = new google.maps.Marker({
position: location,
map: mapCanvas,
labelContent : label
});
div_hide();
}
function setZoomLimit(map, mapTypeId){
//Gets MapTypeRegistry
var mapTypeRegistry = map.mapTypes;
//Gets the specified MapType
var mapType = mapTypeRegistry.get(mapTypeId);
//Sets limits to MapType
mapType.maxZoom = 15; //It doesn't work with SATELLITE and HYBRID maptypes.
mapType.minZoom = 15;
}
function CSVToArray(strData, strDelimiter ){
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ";");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
), "gi");
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData ))
{
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter))
{
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else
{
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
<body>
CSS
/* Author : iMomen
Website: www.iMomen.com
E-mail : Coder#iMomen.com
*/
#mapContainer {
height: 100%;
width: 100%;
margin-left: 0px;
margin-right: 0px;
margin-bottom: 0px;
margin-top: 0px;
position: relative;
}
#map {
height: 100%;
}
.gm-style-mtc {
display: none;
}
.gmnoprint {
display: none;
}
#abc {
width:100%;
height:100%;
top:0;
left:0;
display:none;
position:fixed;
background-color: rgba(0,0,0, .5);
overflow:auto;
}
div#popupContact {
width: 350px; /*can be in percentage also.*/
margin: 0;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
background-color: #ffffff;
}
div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
html, body {
height:100%;
width: 100%;
margin-left: 0px;
margin-right: 0px;
margin-bottom: 0px;
margin-top: 0px;
overflow:hidden;
}
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
a {
color:#FF3679;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.container {
width: 350px;
margin-left: auto;
margin-right: auto;
}
.reg_section {
padding:0;
margin: 10px 0;
border-bottom: 1px dotted #eee;
}
.reg_section h3 {
font-size: 13px;
margin: 5px 0;
color: #C4A2A2;
}
/* Form */
.register {
text-align: center;
position: relative;
padding: 20px 20px 20px 20px;
background: #fff;
border-radius: 3px;
}
.register:before {
content: '';
position: absolute;
top: -8px;
right: -8px;
bottom: -8px;
left: -8px;
z-index: -1;
background:rgba(255, 173, 200, 0.08);
border-radius:7px;
-webkit-border-radius: 7px;
}
.register h1 {
margin: -20px -20px 0;
line-height: 40px;
font-size: 15px;
font-weight: bold;
color:#694551;
text-align: center;
border-bottom:1px solid #EDEDED;
border-radius: 3px 3px 0 0;
-webkit-box-shadow: 0 1px #f5f5f5;
-moz-box-shadow: 0 1px #f5f5f5;
box-shadow: 0 1px #f5f5f5;
}
.register input[type=text], .register input[type=password] ,.register select,.register textarea {
width: 278px;
}
.register p.terms {
float: left;
line-height: 31px;
}
.register p.terms label {
font-size: 12px;
color: #777;
cursor: pointer;
}
.register p.terms input {
position: relative;
bottom: 1px;
margin-right: 4px;
vertical-align: middle;
}
.register-help {
margin: 20px 0;
font-size: 11px;
text-align: center;
color:#FFFFFF;
}
.register-help a {
color:#FF3679;
text-shadow:0 1px #1E0E13;
}
:-moz-placeholder {
color: #404040 !important;
font-size: 13px;
}
::-webkit-input-placeholder {
color: #ccc;
font-size: 13px;
}
input {
font-family:"Trebuchet MS",tahoma;
font-size: 14px;
}
input[type=text], input[type=password] ,.register select,.register textarea {
margin: 5px;
padding: 0 10px;
height: 34px;
color: #404040;
background: #fff;
border-width: 1px;
border-style: solid;
border-color: #c4c4c4 #d1d1d1 #d4d4d4;
border-radius:3px;
--webkit-border-radius: 5px;
outline:3px solid rgba(200, 105, 137, 0.09);
-moz-outline-radius:7px;
-webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
-moz-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
margin:10px 0;
}
input[type=text]:focus, input[type=password]:focus{
border-color:#FFF7F9;
outline-color:rgba(254, 225, 235, 0.7);
outline-offset: 0;
}
input[type=button] {
padding:0 0px;
height: 29px;
width: 100px;
font-size: 12px;
font-weight: bold;
color:#FFFFFF;
text-shadow:0 1px #4D1124;
border-width: 1px;
border-style: solid;
border-color:#693647;
outline: none;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
background-color: #7D0F33;
}
input[type=button]:active {
background: #7D0F33;
-webkit-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
-moz-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
}
.lt-ie9 input[type=text], .lt-ie9 input[type=password] {
line-height: 34px;
}
.register select {
padding:6px 10px;
width: 300px;
color: #777777;
}
.register textarea {
height: 50px;
padding: 10px;
color: #404040;
}
/* About */
.about {
margin:10px auto;
width: 300px;
text-align: center;
color:#EEA5BD;
font-size: 12px;
}
.about a {
padding: 1px 3px;
margin: 0 -1px;
color: #fff;
text-decoration: none;
text-shadow: 0 -1px rgba(0, 0, 0, 0.2);
border-radius: 2px;
}
.about a:hover {
color:#2F0916;
text-shadow: none;
background: #E83671;
}
.links {
zoom: 1;
}
.links:before, .links:after {
content: "";
display: table;
}
.links:after {
clear: both;
}
.links a {
padding: 6px 0;
float: left;
width: 50%;
font-size: 14px;
}
.gm-style-iw {
width: 350px !important;
top: 15px !important;
left: 0px !important;
background-color: #fff;
border-radius: 2px 2px 10px 10px;
}
#iw-container {
margin-bottom: 10px;
}
#iw-container .iw-title {
font-family: 'Open Sans Condensed', sans-serif;
font-size: 22px;
font-weight: 400;
padding: 10px;
background-color: #7D0F33;
color: white;
margin: 0;
border-radius: 2px 2px 0 0;
}
#iw-container .iw-content {
font-size: 13px;
line-height: 18px;
font-weight: 400;
margin-right: 1px;
padding: 15px 5px 20px 15px;
max-height: 140px;
overflow-y: auto;
overflow-x: hidden;
}
.iw-subTitle {
font-size: 16px;
font-weight: 700;
padding: 5px 0;
}
.iw-bottom-gradient {
position: absolute;
width: 326px;
height: 25px;
bottom: 10px;
right: 18px;
background: linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
background: -webkit-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
background: -moz-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
background: -ms-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
}
I think you should store the marker object inside an array of object. Ex:
var arrayOfMarkers = [];
for (var i = 0; i < data.length; i++) {
// Create a lat/long object readable by Google
var myLatlng = new google.maps.LatLng(parseFloat(data[i][0]), parseFloat(data[i][1]));
// Generate a marker from the lat/long object and add it to the map
var marker = new google.maps.Marker({
position: myLatlng,
map: mapCanvas,
title: data[i][2],
description: data[i][3]
});
arrayOfMarkers.push(marker);
}
Then use the arrayOfMarkers to iterate the event listener for each Info Windows
[Updated - Add Ground Overlay after user clicks the marker]
Please see the demo here : http://codepen.io/dannypranoto/pen/PNdvzb
All you need to do is set up a new function for creating a new Ground Overlay with parameters of imageBound
this.instance = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(40.740, -74.18),
zoom: 13,
});
this.addGroundOverlay = function(data) {
var instance = this.instance;
var groundOverlay = new google.maps.GroundOverlay(
'http://i.stack.imgur.com/0mgx2.jpg',data);
groundOverlay.setMap(instance);
}
Then call the function inside the google.maps.event.addListener(marker, ...)
this.addMarker = function(data) {
var Map = this;
var instance = this.instance;
var content = String.format(this.contentTemplate, data.image_url, data.name, data.summary);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
title: data.name
});
marker.setMap(instance);
google.maps.event.addListener(marker, 'click', function() {
var imageBound = {
north: 40.773941,
south: 40.712216,
east: -74.12544,
west: -74.22655
}
Map.addGroundOverlay(imageBound);
});
}

CartoDB: Buttons switching between layers

sorry, I am very new to this. I want something similar to this here CartoDB multiple layer toggle,
only that I am not adding a SQL queried layer, but one from an URL. Each button should make one layer active, one layer at a time and always only one layer visible.
Thanks for any hint!
Best, Wolfram
<html>
<head>
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/themes/css/cartodb.css" />
<script src="http://libs.cartocdn.com/cartodb.js/v3/cartodb.js"></script>
<!--[if lte IE 8]>
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v2/themes/css/cartodb.ie.css" />
<![endif]-->
<style>
html, body {width:100%; height:100%; padding: 0; margin: 0;}
#cartodb-map { width: 100%; height:100%; background: black;}
#menu { position: absolute; top: 5px; right: 10px; width: 400px; height:60px; background: transparent; z-index:10;}
#menu a {
margin: 15px 10px 0 0;
float: right;
vertical-align: baseline;
width: 100px;
padding: 10px;
text-align: center;
font: bold 11px "Helvetica",Arial;
line-height: normal;
color: #555;
border-radius: 4px;
border: 1px solid #777777;
background: #ffffff;
text-decoration: none;
cursor: pointer;
}
#menu a.selected,
#menu a:hover {
color: #F84F40;
}
</style>
<script>
var map;
function init(){
// initiate leaflet map
map = new L.Map('cartodb-map', {
center: [-22.8,-43.15],
zoom: 10
})
L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.png', {
attribution: ' '
}).addTo(map);
}
var layerUrl1 = 'https://riomapia.cartodb.com/api/v2/viz/d79239a6-51af-11e5-ba37-0e853d047bba/viz.json';
var layerUrl2 = 'https://riomapia.cartodb.com/api/v2/viz/633f93e0-51b0-11e5-b512-0e4fddd5de28/viz.json';
var layerUrl3 = 'https://riomapia.cartodb.com/api/v2/viz/4fa846f0-51b1-11e5-bd3c-0e853d047bba/viz.json';
function showLayer(layerToShow) {
//turn off all layers
layer.forEach(function(i) {
i.hide()
});
switch (layerToShow.id) {
case "Renda1":
layer.show(layerUrl1);
break;
case "Renda2":
layer.show(layerUrl2);
break;
case "Renda3":
layer.show(layerUrl3);
break;
}
return true;
}
</script>
</head>
<body onload="init()">
<div id='cartodb-map'></div>
<div id='menu'>
Renda domiciliar por pessoa
Pessoas < R$ 140
Pessoas < R$ 70
</div>
</body>
</html>
I'm not sure that you can do this (but I'm not certain) - however, I looked at the json files that you are linking to, and I see that the data is from Open Street Map. Have you tried looking at this tutorial?
http://docs.cartodb.com/tutorials/osm.html
Maybe that will help?

MapBox API exclusive layer switcher

I have thoroughly searched MapBox support and Stack Overflow for an answer on how to create an exclusive layer switcher using the latest MapBox API (1.6.1 as of now). Exclusive in this case means that only 1 layer can be visible/active at a time. I do not want to use the Leaflet Layers Control for design reasons.
With a little help, I have come up with this example, which almost works:
http://bl.ocks.org/sarahkhank/0e5d81998d2d0876856c
For some reason, adding and removing the gridControl breaks the loop. If you use this structure to just add/remove the tileLayer with no gridLayer or gridControl, it works fine. But when you add the grid elements, the last element in the array doesn't show up and messes up the rest of the loop. (In this case 'far'.)
Does anyone have any idea why this is happening? This type of layer switcher is often asked about on MapBox support, so I'm sure many people would be happy to see this come to life. Thanks for your help!!
Posting full code here at the bottom in case my bl.ocks link ever breaks.
<html>
<head>
<title>DC Zoning Map</title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src='http://api.tiles.mapbox.com/mapbox.js/v1.6.1/mapbox.js'></script>
<link href='http://api.tiles.mapbox.com/mapbox.js/v1.6.1/mapbox.css' rel='stylesheet' />
</head>
<body>
<style>
#zoning-map-container {
position:relative;
float: right;
display: inline;
}
#map_zoning {
position: relative;
float: left;
clear: both;
width:45%;
min-width: 500px;
height: 500px;
right:20px;
margin-top: 10px;
margin-right: 10px;
border: 1px solid #bbb;
}
#map-ui-zoning {
position:relative;
float: left;
list-style:none;
margin:0;padding:0;
left: -20px;
}
#map-ui-zoning a {
font-family: 'Carrois Gothic', sans-serif;
font-size: 12px;
font-weight: 400;
background:#FFF;
color:#5698D0;
float: left;
margin:0;
border:1px solid #BBB;
border-width: 1px 1px 1px 0;
max-width:100px;
padding:8px;
text-decoration:none;
}
#map-ui-zoning li {
display: inline;
}
#map-ui-zoning a:hover { background:#ECF5FA; }
#map-ui-zoning li:last-child a {
border-bottom-width:1px;
-webkit-border-radius:0 3px 3px 0;
border-radius:0 3px 3px 0;
}
#map-ui-zoning li:first-child a {
border-left-width: 1px;
-webkit-border-radius:3px 0 0 3px;
border-radius:3px 0 0 3px;
}
#map-ui-zoning a.active {
background:#5698D0;
border-color:#5698D0;
border-top-color:#BBB;
color:#FFF;
}
.map-tooltip .zone {
font-size: 10px;
line-height: 13px;
font-weight: bold;
}
.map-tooltip .desc {
font-size: 10px;
line-height: 13px;
padding-bottom: 3px;
}
.map-tooltip .focus {
font-size: 13px;
line-height: 16px;
font-weight: bold;
}
.map-tooltip .info {
font-size: 11px;
line-height: 16px;
}
</style>
<div id='zoning-map-container'>
<ul id='map-ui-zoning'>
<li>Maximum Stories</li>
<li>Maximum Height</li>
<li>Maximum FAR</li>
</ul>
<div id='map_zoning'></div>
</div>
<script type='text/javascript'>
var map = L.mapbox.map('map_zoning');
var stamenLayer = L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.png', {
attribution: 'Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA.'
}).addTo(map);
map.setView([38.908, -77.029], 11);
var ui = document.getElementById('map-ui-zoning');
var stories = L.mapbox.tileLayer('sarah.28n6ogvi');
var storiesGrid = L.mapbox.gridLayer('sarah.28n6ogvi');
var storiesGridControl = L.mapbox.gridControl(storiesGrid, {follow: false});
var height = L.mapbox.tileLayer('sarah.ofjsv2t9');
var heightGrid = L.mapbox.gridLayer('sarah.ofjsv2t9');
var heightGridControl = L.mapbox.gridControl(heightGrid, {follow: false});
var far = L.mapbox.tileLayer('sarah.2w9x80k9');
var farGrid = L.mapbox.gridLayer('sarah.2w9x80k9');
var farGridControl = L.mapbox.gridControl(farGrid, {follow: false});
var layers = [{
'name': 'stories',
'layer': stories,
'gridLayer': storiesGrid,
'gridControl': storiesGridControl
},
{
'name': 'height',
'layer': height,
'gridLayer': heightGrid,
'gridControl': heightGridControl
},
{
'name': 'far',
'layer': far,
'gridLayer': farGrid,
'gridControl': farGridControl
}
];
$(document).ready(function(layer){
map.addLayer(stories);
map.addLayer(storiesGrid);
map.addControl(storiesGridControl);
});
$('#map-ui-zoning li a').on('click', function() {
$('#map-ui-zoning li a').removeClass('active');
var $el = $(this);
layers.forEach(function(layer) {
if ($el.data('name') !== layer['name']){
map.removeLayer(layer['layer']);
map.removeLayer(layer['gridLayer']);
map.removeControl(layer['gridControl']);
}
else {
map.addLayer(layer['layer']);
map.addLayer(layer['gridLayer']);
map.addControl(layer['gridControl']);
$el.addClass('active');
}
});
});
</script>
I think that when you call map.removeControl(layer['gridControl']) or more generally map.removeLayer you dont test if the layer is already added to the map because otherwise it mapboxjs will try to delete an element that does not exist and this is where your code gets broken .
if ($el.data('name') !== layer['name'])
needs to become
if ($el.data('name') !== layer['name'] && map.hasLayer(layer))
of course you need to change your else statement accordingly .
here is your example running
http://bl.ocks.org/radproject/31c48b1a7610e353d495

Categories