Resize dojox chart on mobile screen - javascript

I am using this Info window with chart ESRI tutorial.
And I would like to customize the dojox pie chart for smaller screens:
#media only screen
and (max-device-width: 320px) {
...
}
Is it possible to use custom dojox chart sizes for custom screen sizes ?
For example the pie chart to be {width: 60px; height: 60px} only when loading on a screen with max-device-width: 320px ?

Yes, It is possible.
However I am afraid that you can not achieve this only by CSS, Because the size of chart depends on various factors. like chart radius, map infoWindow size, container size etc.
Solution-
You can change above values based on the screen size dynamically, you can use window resize event for it.. this is how you can achieve this.
Below is the working code-
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Info Window with Chart</title>
<link rel="stylesheet" href="https://js.arcgis.com/3.20/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="https://js.arcgis.com/3.20/esri/css/esri.css">
<style>
html, body, #map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
.chart {
width:100px;
height:100px;
padding:0px !important;
}
</style>
<script src="https://js.arcgis.com/3.20/"></script>
<script>
var map;
// Try other themes: Julie, CubanShirts, PrimaryColors, Charged, BlueDusk, Bahamation, Harmony, Shrooms
var theme = "Wetland";
require([
"esri/map", "esri/layers/FeatureLayer",
"esri/dijit/InfoWindow", "esri/InfoTemplate",
"esri/symbols/SimpleFillSymbol", "esri/renderers/SimpleRenderer",
"dijit/layout/ContentPane", "dijit/layout/TabContainer",
"dojox/charting/Chart2D", "dojox/charting/plot2d/Pie",
"dojox/charting/action2d/Highlight", "dojox/charting/action2d/MoveSlice", "dojox/charting/action2d/Tooltip",
"dojox/charting/themes/" + theme,
"dojo/dom-construct", "dojo/dom-class",
"dojo/number", "dojo/domReady!"
], function(
Map, FeatureLayer,
InfoWindow, InfoTemplate,
SimpleFillSymbol, SimpleRenderer,
ContentPane, TabContainer,
Chart2D, Pie,
Highlight, MoveSlice, Tooltip,
dojoxTheme,
domConstruct, domClass,
number, parser
) {
// Use the info window instead of the popup.
var infoWindow = new InfoWindow(null, domConstruct.create("div"));
infoWindow.startup();
map = new Map("map", {
basemap: "streets",
center: [-113.405, 43.521],
infoWindow: infoWindow,
zoom: 6
});
map.infoWindow.resize(180, 200);
var template = new esri.InfoTemplate();
// Flag icons are from http://twitter.com/thefella, released under creative commons.
template.setTitle("<b><img src='flags/${STATE_ABBR}.png'> ${STATE_NAME}</b>");
template.setContent(getWindowContent);
var statesLayer = new FeatureLayer("https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5", {
mode: FeatureLayer.MODE_ONDEMAND,
infoTemplate: template,
outFields: ["*"]
});
var symbol = new SimpleFillSymbol();
statesLayer.setRenderer(new SimpleRenderer(symbol));
map.addLayer(statesLayer);
function getWindowContent(graphic) {
// Make a tab container.
var tc = new TabContainer({
style: "width:100%;height:100%;"
}, domConstruct.create("div"));
// Display attribute information.
var cp1 = new ContentPane({
title: "Details",
content: "<a target='_blank' href='https://en.wikipedia.org/wiki/" +
graphic.attributes.STATE_NAME + "'>Wikipedia Entry</a><br><br>Median Age: " +
graphic.attributes.MED_AGE + "<br>Median Age (Male): " +
graphic.attributes.MED_AGE_M + "<br>Median Age (Female): " +
graphic.attributes.MED_AGE_F
});
// Display a dojo pie chart for the male/female percentage.
var cp2 = new ContentPane({
title: "Pie Chart"
});
tc.addChild(cp1);
tc.addChild(cp2);
// Create the chart that will display in the second tab.
var c = domConstruct.create("div", {
id: "demoChart"
}, domConstruct.create("div"));
var chart = new Chart2D(c);
domClass.add(chart, "chart");
// Apply a color theme to the chart.
chart.setTheme(dojoxTheme);
chart.addPlot("default", {
type: "Pie",
radius: 45,
htmlLabels: true
});
tc.watch("selectedChildWidget", function(name, oldVal, newVal){
if ( newVal.title === "Pie Chart" ) {
chart.resize(100,100);
}
});
// Calculate percent male/female.
var total = graphic.attributes.POP2000;
var male = number.round(graphic.attributes.MALES / total * 100, 2);
var female = number.round(graphic.attributes.FEMALES / total * 100, 2);
chart.addSeries("PopulationSplit", [{
y: male,
tooltip: male,
text: "Male"
}, {
y: female,
tooltip: female,
text: "Female"
}]);
//highlight the chart and display tooltips when you mouse over a slice.
new Highlight(chart, "default");
new Tooltip(chart, "default");
new MoveSlice(chart, "default");
cp2.set("content", chart.node);
return tc.domNode;
}
});
</script>
</head>
<body class="claro">
<div id="map"></div>
</body>
</html>
Hoping this will help you :)

Related

Prevent multiple markerClusterGroup icons from overlapping in Leaflet

I have two seperate markerClusterGroups that occasionally overlap. Is there anyway to prevent this? In my actual code, I am using a custom Icon for one of the cluster groups so that I can tell the difference between the two cluster types. However, it wasn't neccessary for this example so I left that part out for the sake of simplicity.
var map = L.map("map");
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
map.setView([48.85, 2.35], 12);
var mcg = L.markerClusterGroup().addTo(map);
var mcg2 = L.markerClusterGroup().addTo(map);
L.marker([48.85, 2.35]).addTo(mcg);
L.marker([48.85, 2.34]).addTo(mcg);
for(var i=0;i<40;i++){
L.marker([48.85, 2.34091]).addTo(mcg2);
}
Here is an example of what I mean:
http://plnkr.co/edit/yqIhI7RMsp9A7I3AwGnY?p=preview
The requirement states that the markers in category 1 must cluster separately from markers in category 2. However both types must be displayed on the map at the same time.
Is there anyway to prevent this?
Not with several Leaflet.markercluster groups as you did.
Think about it: where should the cluster icons positions be computed, when a given group has no data about another group?
You may have several possible workarounds and/or other libraries that may better fit your need, without having to re-write a clustering algorithm yourself.
For example, a popular alternative to show different categories while clustering is the PruneCluster plugin:
PruneCluster is a fast and realtime marker clustering library.
It's working with Leaflet as an alternative to Leaflet.markercluster.
Excerpt from PruneCluster home page
Another possible workaround would be to merge all categories into the same Marker Cluster Group, but have the latter's cluster icon customized so that they render similarly as the above PruneCluster screenshot, or even render fake icons for each category:
function customClusterIcon(cluster) {
// Count number of markers from each category.
var markers = cluster.getAllChildMarkers();
var cat1count = 0;
var cat2count = 0;
for (var marker of markers) {
var category = marker.options.category;
if (category && category === 'cat2') {
cat2count += 1;
} else {
cat1count += 1;
}
}
// Generate the cluster icon depending on presence of Markers from different categories.
if (cat2count === 0) {
return L.divIcon({
html: cat1count,
className: 'cat1cluster cluster',
iconSize: [20, 20]
});
} else if (cat1count === 0) {
return L.divIcon({
html: cat2count,
className: 'cat2cluster cluster',
iconSize: [20, 20]
});
} else {
return L.divIcon({
html: `
<div class="cat1cluster cluster">${cat1count}</div>
<div class="cat2cluster cluster">${cat2count}</div>
`,
className: '',
iconSize: [45, 20]
});
}
}
var paris = [48.86, 2.35];
var parisLeft = [48.86, 2.25];
var parisRight = [48.86, 2.45];
var map = L.map('map', {
maxZoom: 18
}).setView(paris, 11);
var mcg = L.markerClusterGroup({
iconCreateFunction: customClusterIcon
}).addTo(map);
var category1 = L.layerGroup();
var category2 = L.layerGroup();
var cat2style = {
color: 'red',
category: 'cat2'
};
var markerA = L.circleMarker(paris).addTo(category1);
var markerB = L.circleMarker(paris).addTo(category1);
var markerC = L.circleMarker(paris, cat2style).addTo(category2);
var markerD = L.circleMarker(paris, cat2style).addTo(category2);
var markerE = L.circleMarker(parisLeft).addTo(category1);
var markerF = L.circleMarker(parisLeft).addTo(category1);
var markerG = L.circleMarker(parisRight, cat2style).addTo(category2);
var markerH = L.circleMarker(parisRight, cat2style).addTo(category2);
mcg.addLayers([category1, category2]);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
html,
body,
#map {
height: 100%;
margin: 0;
}
.cat1cluster {
background-color: #3388ff;
}
.cat2cluster {
background-color: red;
}
.cluster {
width: 20px;
height: 20px;
display: inline-block;
text-align: center;
}
<!-- Leaflet assets -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="" />
<script src="https://unpkg.com/leaflet#1.3.4/dist/leaflet-src.js" integrity="sha512-+ZaXMZ7sjFMiCigvm8WjllFy6g3aou3+GZngAtugLzrmPFKFK7yjSri0XnElvCTu/PrifAYQuxZTybAEkA8VOA==" crossorigin=""></script>
<!-- Leaflet.markercluster assets -->
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster#1.4.1/dist/MarkerCluster.css">
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster#1.4.1/dist/MarkerCluster.Default.css">
<script src="https://unpkg.com/leaflet.markercluster#1.4.1/dist/leaflet.markercluster-src.js"></script>
<div id="map"></div>
Then if you wish you can further customize the spiderfication so that it shows Markers only from the clicked category cluster icon, and similar for the hovering polygon.

JavaScript If statement and Combo box functionality

I have two combo box's working independently. I would like to get them to work together. I either get State name queried or Farm Acreage queried. I cannot get them both to filter together.
Query Texas and 4 Acres. Get all the 4 acre counties in Texas. Right now it will either give me All of Texas or All 4 acre counties in the US.
The if statements are in the "app" object.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no" />
<title>Drop Down Test</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.10/js/dojo/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.10/js/esri/css/esri.css">
<style>
html,
body,
#mainWindow {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
body {
background-color: #FFF;
overflow: hidden;
font-family: "Trebuchet MS";
}
#header {
height: 3%;
overflow: auto;
}
</style>
<script>
var dojoConfig = {
parseOnLoad: true
};
</script>
<script src="http://js.arcgis.com/3.10/"></script>
<script>
var map;
require([
"esri/map",
"dojo/on",
"esri/tasks/query",
"esri/layers/FeatureLayer",
"dojo/store/Memory",
"dojo/_base/array",
"dojo/_base/lang",
"esri/request",
"dojo/json",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dijit/form/Button",
"dijit/form/ComboBox",
"dojo/domReady!"
], function(
Map, on, Query, FeatureLayer, Memory, array, lang, esriRequest, json
) {
map = new Map("map", {
basemap: "topo",
center: [-98.579729, 39.828366],
zoom: 5
});
var crops = new FeatureLayer("https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/USA_County_Crops_2007/FeatureServer/0", {
mode: FeatureLayer.MODE_SELECTION,
outFields: ["*"]
});
map.addLayers([crops]);
map.on("layers-add-result", lang.hitch(this, function(){
var url = "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/USA_County_Crops_2007/FeatureServer/0/generateRenderer";
var classificationDef = {"type":"uniqueValueDef","uniqueValueFields":["STATE"]};
var classificationDef2 = {"type":"uniqueValueDef","uniqueValueFields":["TotalFarmedAcres"]};
var str = json.stringify(classificationDef);
var str2 = json.stringify(classificationDef2);
esriRequest({
url:url,
content:{
classificationDef:str,
f:'json'
},
handleAs:'json',
callbackParamName:'callback',
timeout:15000
}).then(lang.hitch(this,function(response){
var uniqueValueInfos = response && response.uniqueValueInfos;
if(uniqueValueInfos){
var store2 = new Memory({data:[]});
dijit.byId("uniqueValuesSelect").set('store',store2);
var data = array.map(uniqueValueInfos,lang.hitch(this,function(info,index){
var value = info.value;
//value = parseFloat(value);
var dataItem = {
id:index,
name:value
};
return dataItem;
}));
store2 = new Memory({data:data});
dijit.byId("uniqueValuesSelect").set('store',store2);
}
}),lang.hitch(this,function(error){
console.error(error);
}));
esriRequest({
url:url,
content:{
classificationDef:str2,
f:'json'
},
handleAs:'json',
callbackParamName:'callback',
timeout:15000
}).then(lang.hitch(this,function(response){
var uniqueValueInfos2 = response && response.uniqueValueInfos;
if(uniqueValueInfos2){
var store3 = new Memory({data:[]});
dijit.byId("uniqueValuesSelect2").set('store',store3);
var data2 = array.map(uniqueValueInfos2,lang.hitch(this,function(info,index){
var value2 = info.value;
//value2 = parseFloat(value2);
var dataItem2 = {
id:index,
name:value2
};
return dataItem2;
}));
store3 = new Memory({data:data2});
dijit.byId("uniqueValuesSelect2").set('store',store3);
}
}),lang.hitch(this,function(error){
console.error(error);
}));
}));
app = {
zoomRow: function(id, which){
crops.clearSelection();
var query = new Query();
if(which == "statename"){
query.where = "STATE='" + (id).toString() + "'";
}if(which == "FarmedAcres"){
query.where = "TotalFarmedAcres='" + (id).toString() + "'";
}
console.info(query.where);
query.returnGeometry = true;
crops.selectFeatures(query, FeatureLayer.SELECTION_NEW, function (features) {
//var thePoly = features[0].geometry;
//var theExtent = thePoly.getExtent().expand(2); //Zoom out slightly from the polygon's extent
//map.setExtent(theExtent);
});
}
};
});
</script>
</head>
<body class="claro">
<div id="mainWindow" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline', gutters:false" style="padding:0px;margin:0px;">
<div id="header" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'top'" style="overflow:hidden;border:none;border-bottom: 3px solid #CC9900;font-family: Windows;font-size:14pt; color: #FFFFFF;background: #000000; "> Select a State and total Acres farmed:
<input id="uniqueValuesSelect" data-dojo-type="dijit.form.ComboBox" value="statename" onchange="app.zoomRow(document.getElementById('uniqueValuesSelect').value, 'statename');" />
<input id="uniqueValuesSelect2" data-dojo-type="dijit.form.ComboBox" value="FarmedAcres" onchange="app.zoomRow(document.getElementById('uniqueValuesSelect2').value, 'FarmedAcres');" />
</div>
<div id="map" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'left'" style="width:100%;height:95%;border:none;padding:0px;margin:0px;"></div>
</div>
</body>
</html>
You need to have access to both comboboxes so you can do something like this:
app = {
zoomRow: function(stateId, acresId){
crops.clearSelection();
var query = new Query();
query.where = "STATE='" + (stateId).toString() + "' AND TotalFarmedAcres='" + (acresId).toString() + "'";
console.info(query.where);
query.returnGeometry = true;
crops.selectFeatures(query, FeatureLayer.SELECTION_NEW, function (features) {
//var thePoly = features[0].geometry;
//var theExtent = thePoly.getExtent().expand(2); //Zoom out slightly from the polygon's extent
//map.setExtent(theExtent);
});
}
};
this means that the html should be something like this
<input id="uniqueValuesSelect" data-dojo-type="dijit.form.ComboBox" value="statename" onchange="app.zoomRow(document.getElementById('uniqueValuesSelect').value, document.getElementById('uniqueValuesSelect2').value);" />
<input id="uniqueValuesSelect2" data-dojo-type="dijit.form.ComboBox" value="FarmedAcres" onchange="app.zoomRow(document.getElementById('uniqueValuesSelect').value, document.getElementById('uniqueValuesSelect2').value);" />
Add corresponding validations to stateId, acresId for avoiding null or undefined values

How to pass back value from JS to Python

I wanted to display a 2D Map with Python and then do something with the coordinates of the coursor in the Python code. I cant get the coordinates to the Python Part however.
Heres my code:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWidgets import QWidget,QVBoxLayout, QApplication
from PyQt5.QtWebChannel import QWebChannel
import bs4
maphtml = '''
<!DOCTYPE HTML>
<!DOCTYPE HTML>
<html>
<head>
<meta name="robots" content="index, all" />
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
<title>WebGL Earth API - Side-by-side - Basic Leaflet compatibility</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
<script src="http://www.webglearth.com/v2/api.js"></script>
<script>
var backend;
new QWebChannel(qt.webChannelTransport, function (channel) {
backend = channel.objects.backend;
});
function init() {
var m = {};
start_(L, 'L');
start_(WE, 'WE');
function start_(API, suffix) {
var mapDiv = 'map' + suffix;
var map = API.map(mapDiv, {
center: [51.505, -0.09],
zoom: 4,
dragging: true,
scrollWheelZoom: true,
proxyHost: 'http://srtm.webglearth.com/cgi-bin/corsproxy.fcgi?url='
});
m[suffix] = map;
//Add baselayer
API.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{
attribution: '© OpenStreetMap contributors'
}).addTo(map);
//Add TileJSON overlay
var json = {"profile": "mercator", "name": "Grand Canyon USGS", "format": "png", "bounds": [-112.26379395, 35.98245136, -112.10998535, 36.13343831], "minzoom": 10, "version": "1.0.0", "maxzoom": 16, "center": [-112.18688965, 36.057944835, 13], "type": "overlay", "description": "", "basename": "grandcanyon", "tilejson": "2.0.0", "sheme": "xyz", "tiles": ["http://tileserver.maptiler.com/grandcanyon/{z}/{x}/{y}.png"]};
if (API.tileLayerJSON) {
var overlay2 = API.tileLayerJSON(json, map);
} else {
//If not able to display the overlay, at least move to the same location
map.setView([json.center[1], json.center[0]], json.center[2]);
}
//Add simple marker
var marker = API.marker([json.center[1], json.center[0]]).addTo(map);
marker.bindPopup(suffix, 50);
marker.openPopup();
//Print coordinates of the mouse
map.on('mousemove', function(e) {
document.getElementById('coords').innerHTML = e.latlng.lat + ', ' + e.latlng.lng;
backend.print(e.latlng.lat)
});
}
//Synchronize view
m['L'].on('move', function(e) {
var center = m['L'].getCenter();
var zoom = m['L'].getZoom();
m['WE'].setView([center['lat'], center['lng']], zoom);
});
}
</script>
<style>
html, body{padding: 0; margin: 0; overflow: hidden;}
#mapL, #mapWE {position:absolute !important; top: 0; right: 0; bottom: 0; left: 0;
background-color: #fff; position: absolute !important;}
#mapL {right: 0%;}
#mapWE {left: 100%;}
#coords {position: absolute; bottom: 0;}
</style>
</head>
<body onload="javascript:init()">
<div id="mapL"></div>
<div id="mapWE"></div>
<div id="coords"></div>
</body>
</html>
'''
class Browser(QApplication):
def __init__(self):
QApplication.__init__(self, [])
self.window = QWidget()
self.window.setWindowTitle("Serial GPS Emulator");
self.web = QWebEngineView(self.window)
self.web.setHtml(maphtml)
self.layout = QVBoxLayout(self.window)
self.layout.addWidget(self.web)
self.window.show()
self.exec()
Browser()
It would be good if the code would stay in one file but if its totally impossible to do it in one splitting it is acceptable.
I guess the first step in solving mny Problem would be to call a function from the HTML/JS part as backend.print("test") also doesnt work.
I also noticed that self.exec() Blocks the rest of the code, is there a way to execute any other code while the map is running? Thanks!
I do not see where in your code you have passed the backend.
In this case you must create a Backend class that can be injected, and for a method to be invoked it must be a slot, for this you must use the pyqtSlot() setting, the parameter that it receives depends on what you are sending it, in the case of the e.latlng is a QJsonValue. In the slot you must separate the necessary parts.
import sys
from PyQt5.QtCore import pyqtSlot, QObject, QJsonValue, pyqtSignal, QTimer
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication
maphtml = '''
<!DOCTYPE HTML>
<!DOCTYPE HTML>
<html>
<head>
<meta name="robots" content="index, all" />
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
<title>WebGL Earth API - Side-by-side - Basic Leaflet compatibility</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
<script src="http://www.webglearth.com/v2/api.js"></script>
<script>
var backend;
new QWebChannel(qt.webChannelTransport, function (channel) {
backend = channel.objects.backend;
console.log(backend);
});
function init() {
var m = {};
start_(L, 'L');
start_(WE, 'WE');
function start_(API, suffix) {
var mapDiv = 'map' + suffix;
var map = API.map(mapDiv, {
center: [51.505, -0.09],
zoom: 4,
dragging: true,
scrollWheelZoom: true,
proxyHost: 'http://srtm.webglearth.com/cgi-bin/corsproxy.fcgi?url='
});
m[suffix] = map;
//Add baselayer
API.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{
attribution: '© OpenStreetMap contributors'
}).addTo(map);
//Add TileJSON overlay
var json = {"profile": "mercator", "name": "Grand Canyon USGS", "format": "png", "bounds": [-112.26379395, 35.98245136, -112.10998535, 36.13343831], "minzoom": 10, "version": "1.0.0", "maxzoom": 16, "center": [-112.18688965, 36.057944835, 13], "type": "overlay", "description": "", "basename": "grandcanyon", "tilejson": "2.0.0", "sheme": "xyz", "tiles": ["http://tileserver.maptiler.com/grandcanyon/{z}/{x}/{y}.png"]};
if (API.tileLayerJSON) {
var overlay2 = API.tileLayerJSON(json, map);
} else {
//If not able to display the overlay, at least move to the same location
map.setView([json.center[1], json.center[0]], json.center[2]);
}
//Add simple marker
var marker = API.marker([json.center[1], json.center[0]]).addTo(map);
marker.bindPopup(suffix, 50);
marker.openPopup();
//Print coordinates of the mouse
map.on('mousemove', function(e) {
document.getElementById('coords').innerHTML = e.latlng.lat + ', ' + e.latlng.lng;
backend.print(e.latlng)
});
}
//Synchronize view
m['L'].on('move', function(e) {
var center = m['L'].getCenter();
var zoom = m['L'].getZoom();
m['WE'].setView([center['lat'], center['lng']], zoom);
});
}
</script>
<style>
html, body{padding: 0; margin: 0; overflow: hidden;}
#mapL, #mapWE {position:absolute !important; top: 0; right: 0; bottom: 0; left: 0;
background-color: #fff; position: absolute !important;}
#mapL {right: 0%;}
#mapWE {left: 100%;}
#coords {position: absolute; bottom: 0;}
</style>
</head>
<body onload="javascript:init()">
<div id="mapL"></div>
<div id="mapWE"></div>
<div id="coords"></div>
</body>
</html>
'''
class Backend(QObject):
positionChanged = pyqtSignal(float, float)
def __init__(self, parent=None):
QObject.__init__(self, parent)
self.position = None, None
self.timer = QTimer(self)
self.timer.setInterval(1000)
self.timer.timeout.connect(self.on_timeout)
#pyqtSlot(QJsonValue)
def print(self, val):
coords = val.toObject()
lat, lng = (coords[key].toDouble() for key in ("lat", "lng"))
self.position = lat, lng
if not self.timer.isActive():
self.timer.start()
def on_timeout(self):
self.positionChanged.emit(*self.position)
def foo(lat, lng):
# this function will be called every second.
print(lat, lng)
if __name__ == '__main__':
app = QApplication(sys.argv)
view = QWebEngineView()
view.setWindowTitle("Serial GPS Emulator");
backend = Backend(view)
backend.positionChanged.connect(foo)
channel = QWebChannel()
channel.registerObject('backend', backend)
view.page().setWebChannel(channel)
view.setHtml(maphtml)
view.show()
sys.exit(app.exec_())

I want to change this random function to onclick function

I am actually creating circles on page randomly and I want to draw these onclick function. But Which code I have is random function which randomly distribute on page. So how can I change this code to onclick ?
<!DOCTYPE html>
<html lang='en'>
<head>
<html>
<input type="text" name="test" style="width: 130px; height: 30px "value="" id="text" placeholder="Enter length"/>
</html>
<meta charset='utf-8' />
<script type='text/javascript' src='OpenLayers.js'></script>
<script type='text/javascript'>
var map;
var vector_layer;
function init() {
//Create a map with an empty array of controls
map = new OpenLayers.Map('map_element');
//Create a base layer
var wms_layer = new OpenLayers.Layer.WMS(
'OpenLayers WMS',
'http://vmap0.tiles.osgeo.org/wms/vmap0',
{layers: 'basic'},
{}
);
map.addLayer(wms_layer);
//Add vector layer
vector_layer = new OpenLayers.Layer.Vector('Settlement Vector Layer');
map.addLayer(vector_layer);
var settlement_values = {
4: 'circle'
}
//Create some points
for(var i=0; i<20; i++){
vector_layer.addFeatures([new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(
(Math.floor(Math.random() * 360) - 180),
(Math.floor(Math.random() * 180) - 90)
),
{
'settlement_type': settlement_values[(Math.floor(Math.random() * 15))]
}
)]);
}
//Create a style map object
var vector_style_map = new OpenLayers.StyleMap({});
//ADD RULES
//We need to create a 'lookup table' that contains the desired values
// and corresponding symbolizer
var x=document.getElementById("text").value;
var symbolizers_lookup = {
'circle': {
'fillColor': '#336699','fillOpacity':.8, 'pointRadius':x, 'strokeColor': '#003366', 'strokeWidth':2
}
}
//Now, call addUniqueValueRules and pass in the symbolizer lookups
vector_style_map.addUniqueValueRules('default', 'settlement_type', symbolizers_lookup);
//Add the style map to the vector layer
vector_layer.styleMap = vector_style_map;
if(!map.getCenter()){
map.zoomToMaxExtent();
}
}
</script>
</head>
<body onload='init();'>
<div id='map_element' style='width: 600px; height: 600px;'></div>
</body>
</html>
Change onload to onclick in your body tag.
<body onclick='init();'> <!-- <======== HERE -->
<div id='map_element' style='width: 600px; height: 600px;'></div>
</body>
</html>

Openlayers - display pacific markers popup using marker id and onclick event

I have the following code which addes 3 markers to the map along with there popup boxes what I want to do is have a list of location at bottom of page and using the id of the marker when click a place in the list it just make that places popup appear on the map.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Open Street Map</title>
<style type="text/css">
body { font: normal 10pt Helvetica, Arial; }
#map { width: 100%; height: 100%; border: 0px; padding: 0px; }
</style>
<script src="lib/OpenLayers.js" type="text/javascript"></script>
<script type="text/javascript">
var iconSize = new OpenLayers.Size(21, 25);
var iconOffset = new OpenLayers.Pixel(-(iconSize.w / 2), -iconSize.h);
var icon = new OpenLayers.Icon("img/fourmarker.png",
iconSize, iconOffset);
var zoom, center, currentPopup, map, lyrMarkers;
var popupClass = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
"autoSize": true,
"minSize": new OpenLayers.Size(300, 50),
"maxSize": new OpenLayers.Size(500, 300),
"keepInMap": true
});
var bounds = new OpenLayers.Bounds();
function addMarker(id, lng, lat, info) {
var pt = new OpenLayers.LonLat(lng, lat)
.transform(new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject());
bounds.extend(pt);
var feature = new OpenLayers.Feature(lyrMarkers, pt);
feature.closeBox = true;
feature.popupClass = popupClass;
feature.data.popupContentHTML = info ;
feature.data.overflow = "auto";
var marker = new OpenLayers.Marker(pt, icon.clone());
var markerClick = function(evt) {
if (currentPopup != null && currentPopup.visible()) {
currentPopup.hide();
}
if (this.popup == null) {
this.popup = this.createPopup(this.closeBox);
map.addPopup(this.popup);
this.popup.show();
} else {
this.popup.toggle();
}
currentPopup = this.popup;
OpenLayers.Event.stop(evt);
};
marker.events.register("mousedown", feature, markerClick);
lyrMarkers.addMarker(marker);
}
function initMap() {
var options = {
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326"),
units: "m",
numZoomLevels: 19,
maxResolution: 156543.0339,
maxExtent: new OpenLayers.Bounds(-0.13011, -0.13011, 51.51039, 51.51039)
};
map = new OpenLayers.Map("map", options);
map.addControl(new OpenLayers.Control.DragPan());
var lyrOsm = new OpenLayers.Layer.OSM();
map.addLayer(lyrOsm);
lyrMarkers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(lyrMarkers);
//add marker on given coordinates
addMarker('1',-0.12519,51.51112 , '<b>Tescos</b><br/>Covent garden');
addMarker('2',-0.13264,51.50918 , '<b>Spar</b><br/>Leicester Square');
addMarker('3', -0.12498,51.50807 , '<b>M & S</b><br/>Embankment');
center = bounds.getCenterLonLat();
map.setCenter(center, map.getZoomForExtent(bounds) - 1);
zoom = map.getZoom();
}
</script>
</head>
<body onload="initMap()" style="margin:0; border:0; padding:0; width:1000px; height:500px;">
<div id="map"></div>
</body>
</html>
EXTRA INFORMATION
I am going to add a list to bottom of map like so:
<ul>
<li>location1</li>
<li>location2</li>
<li>location3</li>
</ul>
What i want to get working is when the user clicks so location1 alink then that relevent popup box will show and the other will be removed.
How would this be done.
This very fast example (modify addMarker function):
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Open Street Map</title>
<style type="text/css">
body { font: normal 10pt Helvetica, Arial; }
#map { width: 100%; height: 100%; border: 0px; padding: 0px; }
#list > div { background-color: #aaa; margin-top: 10px; }
</style>
<script src="http://openlayers.org/api/OpenLayers.js" type="text/javascript"> </script>
</head>
<body onload="initMap()" style="margin:0; border:0; padding:0; width:1000px; height:500px;">
<div id="map"></div>
<div id="list" style="width:100%; height: 100%"></div>
</body>
<script type="text/javascript">
var iconSize = new OpenLayers.Size(21, 25);
var iconOffset = new OpenLayers.Pixel(-(iconSize.w / 2), -iconSize.h);
var icon = new OpenLayers.Icon("img/fourmarker.png",
iconSize, iconOffset);
var list = document.getElementById('list');
var zoom, center, currentPopup, map, lyrMarkers;
var popupClass = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
"autoSize": true,
"minSize": new OpenLayers.Size(300, 50),
"maxSize": new OpenLayers.Size(500, 300),
"keepInMap": true
});
var bounds = new OpenLayers.Bounds();
function addMarker(id, lng, lat, info) {
var pt = new OpenLayers.LonLat(lng, lat)
.transform(new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject());
bounds.extend(pt);
var feature = new OpenLayers.Feature(lyrMarkers, pt);
feature.closeBox = true;
feature.popupClass = popupClass;
feature.data.popupContentHTML = info ;
feature.data.overflow = "auto";
var marker = new OpenLayers.Marker(pt, icon.clone());
var markerClick = function(evt) {
if (currentPopup != null && currentPopup.visible()) {
currentPopup.hide();
}
if (this.popup == null) {
this.popup = this.createPopup(this.closeBox);
map.addPopup(this.popup);
this.popup.show();
} else {
this.popup.toggle();
}
currentPopup = this.popup;
OpenLayers.Event.stop(evt);
};
marker.events.register("mousedown", feature, markerClick);
lyrMarkers.addMarker(marker);
// add items
var listItem = OpenLayers.Util.createDiv(this.id, null, null, null, 'relative', null);
listItem.innerHTML = info;
list.appendChild(listItem);
var callback = function(e) {
marker.events.triggerEvent('mousedown');
console.log(marker);
OpenLayers.Event.stop(e);
};
OpenLayers.Event.observe(listItem, "touchend", OpenLayers.Function.bindAsEventListener(callback, this));
OpenLayers.Event.observe(listItem, "click", OpenLayers.Function.bindAsEventListener(callback, this));
}
function initMap() {
var options = {
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326"),
units: "m",
numZoomLevels: 19,
maxResolution: 156543.0339,
maxExtent: new OpenLayers.Bounds(-0.13011, -0.13011, 51.51039, 51.51039)
};
map = new OpenLayers.Map("map", options);
map.addControl(new OpenLayers.Control.DragPan());
var lyrOsm = new OpenLayers.Layer.OSM();
map.addLayer(lyrOsm);
lyrMarkers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(lyrMarkers);
//add marker on given coordinates
addMarker('1',-0.12519,51.51112 , '<b>Tescos</b><br/>Covent garden');
addMarker('2',-0.13264,51.50918 , '<b>Spar</b><br/>Leicester Square');
addMarker('3', -0.12498,51.50807 , '<b>M & S</b><br/>Embankment');
center = bounds.getCenterLonLat();
map.setCenter(center, map.getZoomForExtent(bounds) - 1);
zoom = map.getZoom();
}
</script>
</html>

Categories

Resources