Save and load the position of dynamically created, draggable elements(jQuery-UI) - html

I am in the process of developing an offline web application that mimics a magnet board.
I can dynamicly create the draggable Items and drag them around the screen. Now I want to be able to save the positions and content(just one image per element) of my elements into a file and later load it again.
I want it in a file because it needs to be interchangable between different users.
Here is the javascript of how i dynamicly create my elements:
$("#item1").mousedown(function (e){
var newpin = document.createElement("DIV");
var pinimage = document.createElement("IMG");
pinimage.setAttribute("src", "Media/2D_Container_Alfa.jpg");
pinimage.setAttribute("height", "70px");
newpin.setAttribute("position","relative");
newpin.setAttribute("top","20px");
newpin.setAttribute("left","140px");
newpin.setAttribute("display","block");
newpin.setAttribute("class", "draggable ui-draggable ui-draggable-handle");
newpin.appendChild(pinimage);
document.body.appendChild(newpin);});
TLDR.: I want to save the configuration on my magnet board and be able to load previously saved configurations

You may consider some newer code:
function makePin(event, t, l){
var $pin = $("<div>", {
class: "pin draggable ui-draggable ui-draggable-handle"
}).css({
position: "relative",
top: (t !== undefined ? t + "px" : "20px"),
left: (l !== undefined ? l + "px" : "140px"),
disply: "block"
}).appendTo(".pin-area");
var $pinImage = $("<img>", {
src: "Media/2D_Container_Alfa.jpg"
}).css({
height: "70px"
}).appendTo($pin);
return $pin;
}
function getPins(){
var pins = [];
$(".pin-area .pin").each(function(ind, el){
var pos = $(el).offset();
var imgSrc = $("img", el).attr("src");
pins.push({
top: pos.top,
left: pos.left,
src: imgSrc
});
});
return pins;
}
$("#item1").mousedown(function (e){
makePin(e);
});
Since you did not include any HTML in your post, I would consider the following in relationship to the code above:
<body>
<div class="pin-area">
</div>
</body>
You also did not indicate what would initiate the saving of this data once collected or how it would be loaded. one way to do this is to update once any drag action is completed, binding to stop. You also did not mention where you wanted to store this data. The following makes some assumptions that you will be using Draggable and LocalStorage.
$(".pin").on("dragstop", function(e, ui){
localStorage.setItem("pins", JSON.stringify(getPins()));
});
This will update a locally stored variable with JSON text each time a pin is moved.
function loadPins(){
var pins = JSON.parse(localStorage.getItems("pins"));
if(pins !== undefined){
$.each(pins, function(k, v){
makePin(null, v.top, v.left);
});
}
}
This function would then be able to load those pins. You'd want to execute this function just before you close your jQuery block. A small example of it all put together. You will need to do more testing and adjusting to fit your needs.
$(function() {
function makePin(event, t, l) {
var $pin = $("<div>", {
class: "pin draggable ui-draggable ui-draggable-handle"
}).css({
position: "relative",
top: (t !== undefined ? t + "px" : "20px"),
left: (l !== undefined ? l + "px" : "140px"),
disply: "block"
}).appendTo(".pin-area");
var $pinImage = $("<img>", {
src: $(".example-image").attr("src")
}).css({
height: "70px"
}).appendTo($pin);
$pin.draggable();
return $pin;
}
function getPins() {
var pins = [];
$(".pin-area .pin").each(function(ind, el) {
var pos = $(el).offset();
var imgSrc = $("img", el).attr("src");
pins.push({
top: pos.top,
left: pos.left,
src: imgSrc
});
});
return pins;
}
function loadPins() {
var pins = JSON.parse(localStorage.getItems("pins"));
if (pins !== undefined) {
$.each(pins, function(k, v) {
makePin(null, v.top, v.left);
});
}
}
$(".pin").on("dragstop", function(e, ui) {
localStorage.setItem("pins", JSON.stringify(getPins()));
});
$(".pin-area").mousedown(function(e) {
makePin(e);
});
loadPins();
});
.pin-area {
width: 1200px;
height: 630px;
border: 1px solid #222;
background-image: url("https://www2.lbl.gov/assets/img/maps/sitemap.jpg");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="pin-area">
</div>
<p>Example Pin:</p><img class="example-image" style="height: 70px;" src="https://www.clker.com/cliparts/r/R/m/q/E/6/orange-pin-th.png">

Related

Change an img, but not with filter in css [duplicate]

This question already has answers here:
How to save image from canvas with CSS filters
(4 answers)
Closed 1 year ago.
I am working on a photo editor and I want to download the edited image after the user makes the necessary changes on the original one. So the filter value depends on the user and is not constant
The changes are working fine but when I click download I get the original one instead of the modified one. Does anyone have any ideas on how I can proceed further? (P.S. I searched all over Stack Overflow and tried to implement every solution in my code but nothing's working)
const canvas = document.getElementById("img");
const ctx = canvas.getContext("2d");
let img = new Image();
let fileName = "";
const downloadBtn = document.getElementById("download-btn");
const uploadFile = document.getElementById("upload-file");
const revertBtn = document.getElementById("revert-btn");
// Upload File
uploadFile.addEventListener("change", () => {
// Get File
const file = document.getElementById("upload-file").files[0];
// Init FileReader API
const reader = new FileReader();
// Check for file
if (file) {
// Set file name
fileName = file.name;
// Read data as URL
reader.readAsDataURL(file);
}
// Add image to canvas
reader.addEventListener(
"load",
() => {
// Create image
img = new Image();
// Set image src
img.src = reader.result;
// On image load add to canvas
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
canvas.removeAttribute("data-caman-id");
};
},
false
);
});
// Download Event
downloadBtn.addEventListener("click", () => {
// Get ext
const fileExtension = fileName.slice(-4);
// Init new filename
let newFilename;
// Check image type
if (fileExtension === ".jpg" || fileExtension === ".png") {
// new filename
newFilename = fileName.substring(0, fileName.length - 4) + "-edited.jpg";
}
// Call download
download(canvas, newFilename);
});
// Download
function download(canvas, filename) {
// Init event
let e;
// Create link
const link = document.createElement("a");
// Set props
link.download = filename;
link.href = canvas.toDataURL("image/jpeg", 0.8);
// New mouse event
e = new MouseEvent("click");
// Dispatch event
link.dispatchEvent(e);
}
const options = {
sepia: 0,
rotation: 0,
scale: 1,
};
function setSepia(e) {
options.sepia = e.value;
document.getElementById('Amount').innerHTML = "(" + e.value + ")";
redraw();
}
let rotation = 0;
function RotateImg() {
rotation += 90;
if (rotation == 360) {
rotation = 0;
}
options.rotation = rotation;
redraw();
}
let scale = 1
function flipping() {
scale -= 2
if (scale <= -2) {
scale = 1;
}
options.scale = scale;
redraw();
}
let invertVal = 0
function invert() {
invertVal += 100
if (invertVal > 100) {
invertVal = 0
}
options.invertVal = invertVal;
redraw();
}
function redraw() {
document.getElementById("img").style["webkitFilter"] = "sepia(" + options.sepia + ")
grayscale(" + options.grayscale + ") brightness(" + options.brightness + ") contrast(" +
options.contrast + ") opacity(" + options.opacity + ") invert(" + options.invertVal + ")"; document.querySelector("img").style.transform = `rotate(${options.rotation}deg)
scaleX(${options.scale})`;
}
<!-- class="custom-file-label" -->
<p><input type="file" id="upload-file">upload</input>
</p>
<p><label for="upload-file">Upload Image</label></p>
<p><canvas id="img"></canvas></p>
<button id="download-btn" class="btn btn-primary btn-block">Download</button>
<div class="sidenav">
<label for="filter-select">FILTER AND ADJUST</label>
<div class="slider">
<p style="color: aliceblue;">Sepia</p>
<input id="sepia" type="range" oninput="setSepia(this);" value="0" step="0.1" min="0" max="1"><span id="Amount" style="color: white;"> (0)</span><br /><br>
</div>
<label onclick="RotateImg()">ROTATE</label>
<label onclick="flipping()">FLIP</label>
</div>
I tried to run your code without success but I got the idea of what you'd like to do so I started building an image editor that should address many of your doubts
I'll leave here some considerations before:
I started on the backbone of this nice editor sample
I'm keeping the original file in <img> and I'm putting the edited image in a <canvas>
the previewFiles() method is used to set the two images and the most comes from this page
as you were correctly doing and as suggested by this question, you will need <canvas> to be able to save the image with CSS filters applied
I will apply the multiple filters as shown by this great example
and then we will download the edited image [actually <canvas>] following this other great example
NOTE: when I tried to run the example in the StackOverflow editor [this one below] I couldn't really download the image but it works if you run the same code in JSFiddle
NOTE: I tested it on Chrome but I would check more in depth with regards to browser compatibility, if this can be an issue
// checking activity on filters values
// calling the apply_filter method as soon as a slider is moved or set into a position
$(document).ready(function() {
$(".range").change(apply_filter).mousemove(apply_filter);
});
// global variable
const original_image = document.getElementById('original_image_preview');
// setting canva size and return its context to drawing functions
function initializeCanva() {
// creating the additional canva to show the filters action
const canvas = document.getElementById('edited_image_canva');
const ctx = canvas.getContext('2d');
// assigning it the same size of the original image preview
canvas.width = original_image.width;
canvas.height = original_image.height;
return ctx;
}
// loading and previewing the files
function previewFiles() {
const preview = document.querySelector('img');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
// the load event is fired only when a file has been read successfully, unlike loadend - because we need a success to get started
reader.addEventListener("load", function() {
// returning the file content
preview.src = reader.result;
// creating the canva to reflect the edits immediately after the original image has been loaded
const ctx = initializeCanva();
// drawing the original image on the canva
ctx.drawImage(original_image, 0, 0, original_image.width, original_image.height);
}, false);
// reading the contents of the specified [image] file
// when the read operation is successfully finished, the load event is triggered - at that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string
if (file) {
reader.readAsDataURL(file);
}
}
// called everytime a slider is hovered or moved around
// atm needed also to show the canva after the original image has been loaded
function apply_filter() {
// getting the filter values from the sliders elements
var grayscale_val = $("#grayscale").val();
//console.log(grayscale_val + "%");
var blur_val = $("#blur").val();
var exposure_val = $("#exposure").val();
var sepia_val = $("#sepia").val();
var opacity_val = $("#opacity").val();
// getting the context where to apply the changes
const ctx = initializeCanva();
// creating the filter from sliders values
ctx.filter = 'grayscale(' + grayscale_val + '%) blur(' + blur_val + 'px) brightness(' + exposure_val + '%) sepia(' + sepia_val + '%) opacity(' + opacity_val + '%)';
// console.log(ctx.filter);
// applying the filter on the original image
ctx.drawImage(original_image, 0, 0, original_image.width, original_image.height);
}
// triggered by clicking on the download button
function download() {
//console.log("asking for download");
// keeping the same image quality
var data = edited_image_canva.toDataURL("image/png", 1);
// create temporary link
var tmpLink = document.createElement('a');
tmpLink.download = 'edited_image.png'; // set the name of the download file
tmpLink.href = data;
// temporarily add link to body and initiate the download
document.body.appendChild(tmpLink);
tmpLink.click();
document.body.removeChild(tmpLink);
}
body {
text-align: center;
width: 100%;
margin: 0 auto;
padding: 0px;
font-family: Helvetica, Sans-Serif;
background-color: #E6E6E6;
}
#wrapper {
text-align: center;
margin: 0 auto;
padding: 0px;
width: 995px;
}
#edit_controls {
background-color: #A4A4A4;
float: left;
width: 500px;
margin-left: 248px;
}
#edit_controls li {
list-style-type: none;
display: inline-block;
padding: 0px;
margin: 10px;
color: white;
}
#images_div img {
width: 80%;
padding: 20px;
}
#images_div canvas {
border: 3px solid #d3d3d3;
}
button {
margin: 20px;
}
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="wrapper">
<!-- filters area -->
<div id="edit_controls">
<li>GrayScale<br><input id="grayscale" class="range" type="range" min="0" max="100" value="0"></li>
<li>Blur<br><input id="blur" class="range" type="range" min="0" max="10" value="0"></li>
<li>Exposure<br><input id="exposure" class="range" type="range" min="0" max="200" value="100"></li>
<li>Sepia<br><input id="sepia" class="range" type="range" min="0" max="100" value="0"></li>
<li>Opacity<br><input id="opacity" class="range" type="range" min="0" max="100" value="100"></li>
</div>
<!-- images area -->
<div id="images_div">
<!-- accepting only image files -->
<input type="file" accept="image/*" onchange="previewFiles()" style="margin-top: 20px"><br>
<img src="" id="original_image_preview" alt="Waiting for the image to edit...">
<br />Edited Image<br /><br />
<canvas id="edited_image_canva">
Your browser does not support the HTML5 canvas tag
</canvas>
<br />
<button onclick="download()">Download</button>
</div>
</div>
</body>
</html>

Chrome extension web inspector

I want to write a chrome extension where it is possible to mark features on a website and save it in a table, for this, I want to use the Chrome web inspector.
Unfortunately, I am new to this area (chrome plugins) and therefore I am looking for help (links, tutorials, related work etc.) to use the web inspector in my own extension.
Simple example on this website https://ieeexplore.ieee.org/document/1005630.
My idea is to mark for example the date of publication, and the plugin write the complete div to a table.
actually, I found a simple solution.
Sample
http://g.recordit.co/5CCFjXpe8J.gif
It's only a small part of my tool to keep it simple.
The main idea comes from Google Chrome Extension: highlight the div that the mouse is hovering over
'iframe' is the injected sidebar
marker.js contains the script to mark divs
manifest.json
{
"name": "Feature extractor",
"version": "1.0",
"description": "Feature extractor from website",
"permissions": ["activeTab", "declarativeContent", "storage", "contextMenus", "<all_urls>", "tabs"],
"browser_action": {},
"web_accessible_resources": ["iframe.html","iframe.js"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"css": [
"marker.css"
],
"js": [
"js/jquery-1.8.3.min.js",
"marker.js"
]
}
],
"manifest_version": 2
}
background.js
'use strict';
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [new chrome.declarativeContent.PageStateMatcher({
pageUrl: {hostEquals: 'developer.chrome.com'},
})],
actions: [new chrome.declarativeContent.ShowPageAction()]
}]);
});
});
// sidebar
chrome.browserAction.onClicked.addListener(function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id,"toggle");
})
});
// message passing
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
console.log(request);
callback({'request':request});
});
// context menu
var labels = ['author','date','abstract']
for(var label in labels) {
console.log(labels[label])
chrome.contextMenus.create({id: labels[label], "title": labels[label], "contexts":['all']});
}
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (info.menuItemId == labels[0]) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id,labels[0]);
})
}
});
iframe.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/jquery.mobile-1.2.1.min.css" />
<script src="js/jquery-1.8.3.min.js"></script>
<script src="js/jquery.mobile-1.2.1.min.js"></script>
<script src="iframe.js"></script>
</head>
<body>
<button id="send">
send
</button>
<div id="responses">
</div>
</body>
</html>
I need the jQuery.fn.. script to identify the selected div Get unique selector of element in Jquery
iframe.js
// unique selector
jQuery.fn.extend({
getPath: function () {
var path, node = this;
while (node.length) {
var realNode = node[0], name = realNode.localName;
if (!name) break;
name = name.toLowerCase();
var parent = node.parent();
var sameTagSiblings = parent.children(name);
if (sameTagSiblings.length > 1) {
var allSiblings = parent.children();
var index = allSiblings.index(realNode) + 1;
if (index > 1) {
name += ':nth-child(' + index + ')';
}
}
path = name + (path ? '>' + path : '');
node = parent;
}
return path;
}
});
window.addEventListener('DOMContentLoaded', function () {
var callback = function (data) {
$("#responses").append("<div>" + data + "</div>");
};
var send = function () {
chrome.runtime.sendMessage(Date(), callback);
}
chrome.runtime.onMessage.addListener(function(msg, data){
if (msg.command == "append-author") {
$("#responses").append("<div>" + msg.el + "</div>")
}
})
document.getElementById('send').addEventListener('click', send);
});
Google Chrome Extension: highlight the div that the mouse is hovering over
marker.js
// Unique ID for the className.
var MOUSE_VISITED_CLASSNAME = 'crx_mouse_visited';
var MOUSE_MARKED_CLASSNAME = 'crx_mouse_marked';
// Previous dom, that we want to track, so we can remove the previous styling.
var prevDOM = null;
// Mouse listener for any move event on the current document.
document.addEventListener('mousemove', function (e) {
let srcElement = e.srcElement;
// Lets check if our underlying element is a IMG.
if (prevDOM != srcElement && srcElement.nodeName == 'DIV' ) {
// For NPE checking, we check safely. We need to remove the class name
// Since we will be styling the new one after.
if (prevDOM != null) {
prevDOM.classList.remove(MOUSE_VISITED_CLASSNAME);
}
// Add a visited class name to the element. So we can style it.
srcElement.classList.add(MOUSE_VISITED_CLASSNAME);
// The current element is now the previous. So we can remove the class
// during the next ieration.
prevDOM = srcElement;
// console.info(srcElement.currentSrc);
// console.dir(srcElement);
}
}, false);
var iframe = document.createElement('iframe');
iframe.style.background = "green";
iframe.id = "comm-test-container";
iframe.style.height = "100%";
iframe.style.width = "0px";
iframe.style.position = "fixed";
iframe.style.top = "0px";
iframe.style.right = "0px";
iframe.style.zIndex = "9000000000000000000";
iframe.frameBorder = "none";
iframe.src = chrome.extension.getURL("iframe.html")
document.body.appendChild(iframe);
function toggle(){
if(iframe.style.width == "0px") {
iframe.style.width="400px";
} else {
iframe.style.width="0px";
}
}
chrome.runtime.onMessage.addListener(function(msg, sender){
if(msg == "toggle"){
toggle();
}
if(msg == "author") {
prevDOM.classList.add(MOUSE_MARKED_CLASSNAME);
chrome.runtime.sendMessage({command:"append-author",el:prevDOM.innerHTML,selector:$(prevDOM).getPath()}, function(response) {});
}
})
// find unique selector
jQuery.fn.extend({
getPath: function () {
var path, node = this;
while (node.length) {
var realNode = node[0], name = realNode.localName;
if (!name) break;
name = name.toLowerCase();
var parent = node.parent();
var sameTagSiblings = parent.children(name);
if (sameTagSiblings.length > 1) {
var allSiblings = parent.children();
var index = allSiblings.index(realNode) + 1;
if (index > 1) {
name += ':nth-child(' + index + ')';
}
}
path = name + (path ? '>' + path : '');
node = parent;
}
return path;
}
});
marker.css
.crx_mouse_visited {
background-clip: #bcd5eb!important;
outline: 1px dashed #e9af6e!important;
z-index : 0!important;
}
.crx_mouse_marked {
background-clip: #bcd5eb!important;
outline: 5px solid #e9af6e!important;
z-index : 0!important;
}

Custom Parameters get cleared canvas to Json

I am adding svg to canvas and want to set custom Element Parameters. I shows custom parameter when we console log getActiveObject() but when we use canvas.toJSON() Element Parameter node values does not change.
var canvas = new fabric.Canvas('designcontainer'),
/* Save additional attributes in Serialization */
var ElementParameters = {
ElementType:'',
imageType:'',
top:'',
left:'',
colors:'',
isBaseTier:'',
atLevel:''
};
fabric.Object.prototype.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
ElementParameters:{
ElementType:'',
imageType:'',
top:'',
left:'',
colors:'',
isBaseTier:'',
atLevel:''
},
});
};
})(fabric.Object.prototype.toObject);
/* End : Save additional attributes in Serialization */
var Designer = {
addElement: function(e,p){ /* e = element, image src | p = parameters set for image */
if(p.imageType == "svg"){
if(p.ElementType == "caketier"){
var group = [];
console.log('Before ');
console.log(ElementParameters);
$.extend(ElementParameters,p);
console.log('After ');
console.log(ElementParameters);
fabric.loadSVGFromURL(e,function(objects,options){
var shape = fabric.util.groupSVGElements(objects,options);
var bound = shape.getBoundingRect();
shape.set({
left: p.left,
top: p.top,
width:bound.width+2,
height:bound.height,
angle:0,
centeredScaling:true,
ElementParameters:ElementParameters
});
if(shape.paths && baseColor.length > 0){
for(var i = 0;i<shape.paths.length;i++) shape.paths[i].setFill(baseColor[i]);
}
canvas.add(shape);
shape.setControlsVisibility(HideControls);
canvas.renderAll();
},function(item, object) {
object.set('id',item.getAttribute('id'));
group.push(object);
});
}
}
}
}
$(".tierbox").on('click',function(){
var i = $(this).find('img'),
src = i.attr('src'),
param = i.data('parameters');
Designer.addElement(src,param);
});
Now when I call JSON.stringify(json), Element Parameter node does not get overwrite with values set in shape.set() method.
Replace fabric.Object.prototype.toObject = (function (toObject) { ... } to
fabric.Object.prototype.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
ElementParameters:this.ElementParameters
});
};
})(fabric.Object.prototype.toObject);

Call markers based on radio button value

I am trying to call markers to a google map based on a value (year as a string). I thought by putting an on click event to listen for when the radio class is clicked, that I could initialize the $.getJSON and set the value for the year.
How can initialize the $.getJSON call when the radio button is clicked and base the variable yearValue on which radio button is checked?
Also, if I wanted to reset the markers each time a new radio button is clicked, would I need to put all of the markers in an array, set them to the map, then clear the array when a new radio button value is checked (say I choose 2014 instead of 2015?). How can I clear the markers when a new radio button is checked so that I don't see both years at the same time?
var map;
var mapProp;
var url = 'https://data.montgomerycountymd.gov/resource/5pue-gfbe.json?$limit=50000';
var count;
var marker;
var manyCategory = [];
var category = [];
var yearValue;
function initMap() {
mapProp = {
center: new google.maps.LatLng(39.154743, -77.240515),
zoom: 10
};
map = new google.maps.Map(document.getElementById('map'), mapProp);
}
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.open(map, marker);
});
}
$(document).ready(function() {
if ($('input:radio[name="year"]').is("checked")) {
yearValue = $(this).val();
}
initMap();
$('.radioClass').on('click', function() {
$.getJSON(url, function(data) {
count = 0;
for (var i = 0; i < data.length; i++) {
var newDate = data[i].inspectiondate;
if (data[i].violation22 === "Out of Compliance" && newDate.slice(0, 4) === yearValue) {
if (data[i].hasOwnProperty('latitude')) {
count++;
var message = "<div>" + data[i].organization + "<br>" + (data[i].inspectiondate).slice(0, 10) + "</div>";
var uniqueIcon;
if (data[i].category === "Private School" || data[i].category === "Public School- Elementary" || data[i].category === "Public School- High" || data[i].category === "Public School- Middle") {
uniqueIcon = "https://maps.gstatic.com/mapfiles/ms2/micons/blue.png";
} else if (data[i].category === "Market" || data[i].category === "Carry Out" || data[i].category === "Snack Bar" || data[i].category === "Caterer" || data[i].category === "Restaurant") {
uniqueIcon = "https://maps.gstatic.com/mapfiles/ms2/micons/purple.png"
} else if (data[i].category === "Nursing Home" || data[i].category === "Hospital" || data[i].category === "Assisted Living") {
uniqueIcon = "https://maps.gstatic.com/mapfiles/ms2/micons/red.png"
} else {
uniqueIcon = "https://maps.gstatic.com/mapfiles/ms2/micons/yellow.png";
}
marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i].location.latitude, data[i].location.longitude),
title: "Hello, world. I received a food violation in 2015",
animation: google.maps.Animation.DROP,
icon: uniqueIcon,
});
marker.setMap(map);
//console.log(data[i].inspectionresults);
addInfoWindow(marker, message);
manyCategory.push(data[i].category);
}
}
}
//;
$.each(manyCategory, function(i, el) {
if ($.inArray(el, category) === -1) category.push(el);
})
//console.log(count);
//console.log(manyCategory);
//console.log(category);
});
});
});
h1,
#icons,
#radioDiv {
text-align: center;
}
#map {
margin: 0 auto;
width: 700px;
height: 400px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<h1>Rodent Violations</h1>
<div id="radioDiv">
<input type="radio" name="year" value="2015" class="radioClass">2015
<input type="radio" name="year" value="2014" class="radioClass">2014
</div>
<div id="icons">
<img src="https://maps.gstatic.com/mapfiles/ms2/micons/blue.png">School
<img src="https://maps.gstatic.com/mapfiles/ms2/micons/purple.png">Restaurant
<img src="https://maps.gstatic.com/mapfiles/ms2/micons/red.png">Healthcare
<img src="https://maps.gstatic.com/mapfiles/ms2/micons/yellow.png">All other
</div>
<div id="map"></div>
You need an array fo markers globally visibile that hold all the markers you create for let you clean them before you show the new markers.
var myMarkers
add the begin of the callback function clear the markers setting maps to null
$.getJSON(url, function(data) {
count = 0;
for (var i = 0; i < myMarkers.length; i++) {
myMarkers[i].setMap(null);
}
myMarkers = []; // empty the array
.......
popluate the myMArkers Array with all the marker you create
marker.setMap(map);
addInfoWindow(marker, message);
myMarkers.push(marker);

How to move 3D model on Cesium

I wanted to move the model dynamically using keyboard shortcuts. I could not find relevant article on that.
So for now, I'm trying to move the model on click. When click on the model. The model has to move in one direction (increment the value 1 on tick). Find below the sandcastle code for that.
var selectedMesh; var i=0;
var viewer = new Cesium.Viewer('cesiumContainer', {
infoBox: false,
selectionIndicator: false
});
var handle = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
function createModel(url, height) {
viewer.entities.removeAll();
var position = Cesium.Cartesian3.fromDegrees(-123.0744619, 44.0503706, height);
var heading = Cesium.Math.toRadians(135);
var pitch = 0;
var roll = 0;
var orientation = Cesium.Transforms.headingPitchRollQuaternion(position, heading, pitch, roll);
var entity = viewer.entities.add({
name: url,
position: position,
orientation: orientation,
model: {
uri: url,
minimumPixelSize: 128
}
});
viewer.trackedEntity = entity;
viewer.clock.onTick.addEventListener(function () {
if (selectedMesh) {
console.log("Before 0 : " + selectedMesh.primitive.modelMatrix[12]);
selectedMesh.primitive.modelMatrix[12] = selectedMesh.primitive.modelMatrix[12] + 1;
console.log("After 0 : " + selectedMesh.primitive.modelMatrix[12]);
}
});
}
handle.setInputAction(function (movement) {
console.log("LEFT CLICK");
var pick = viewer.scene.pick(movement.position);
if (Cesium.defined(pick) && Cesium.defined(pick.node) && Cesium.defined(pick.mesh)) {
if (!selectedMesh) {
selectedMesh = pick;
}
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
var options = [{
text: 'Aircraft',
onselect: function () {
createModel('../../SampleData/models/CesiumAir/Cesium_Air.bgltf', 5000.0);
}
}, {
text: 'Ground vehicle',
onselect: function () {
createModel('../../SampleData/models/CesiumGround/Cesium_Ground.bgltf', 0);
}
}, {
text: 'Milk truck',
onselect: function () {
createModel('../../SampleData/models/CesiumMilkTruck/CesiumMilkTruck.bgltf', 0);
}
}, {
text: 'Skinned character',
onselect: function () {
createModel('../../SampleData/models/CesiumMan/Cesium_Man.bgltf', 0);
}
}];
Sandcastle.addToolbarMenu(options);
When I click, the model is moving for the first time. After that, It stays on the same place. I've printed the value in the console. It seems the value is not changing. I'm not sure about the problem here. or I'm implementing the transformation wrongly.
If you keep track of the current lat and lon of the entity, and adjust that lat and lon based on user input, all you need to do is update the orientation of the entity.
var lon = // the updated lon
var lat = // updated lat
var position = Cesium.Cartesian3.fromDegrees(lon, lat, height);
var heading = Cesium.Math.toRadians(135);
var pitch = 0;
var roll = 0;
// create an orientation based on the new position
var orientation = Cesium.Transforms.headingPitchRollQuaternion(position, heading, pitch, roll);
Then you just need to update the orientation of the entity.
entity.orientation = orientation;
By changing the value, the models orientation, and therefore position will get updated.