Related
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
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 have to show multiple chart on a HTML page, but i can't make multiple query (directly on a google spreedsheet).
Actually, I have just the first query who is display.
My code :
<html>
<head>
<meta charset="utf-8">
<title>Page de pilotage</title>
<link rel=stylesheet type="text/css" href="style.css">
<script type="text/javascript" src="javascript.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", '1', {packages:['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/xxx/gviz/tq?sheet=visites');
var query2 = new google.visualization.Query('https://docs.google.com/spreadsheets/d/xxx/gviz/tq?sheet=transactions');
query.send(handleQueryResponse);
query2.send(handleQueryResponse);
}
function handleQueryResponse(response) {
var options = {
pointSize: 4,
title: '',
}
var data = response.getDataTable();
var chart = new google.visualization.LineChart(document.getElementById('visites'));
var chart2 = new google.visualization.LineChart(document.getElementById('transactions'));
chart.draw(data, options);
chart2.draw(data, options);
}
</script>
</head>
<body>
<h1>Page de pilotage - KPI/PROGRESSION</h1>
<p>Cette page WEB rassemble des informations générales pour aider au pilotage du site</p>
<h2>PROGRESSION</h2>
<div style="width:1200px;">
<div style="width:599px; float:left;">
<h3>NOMBRE DE VISITES</h3>
<div id="visites" style="height: 280px; z-index: 1; margin-top: -25px; border-right:1px solid #ccc;"></div>
</div>
<div style="width:599px; float:right;">
<h3>NOMBRE DE TRANSACTIONS</h3>
<div id="transactions" style="height: 280px; z-index: 1; margin-top: -25px;"></div>
</div>
</div>
</body>
</html>
I think the problem was on these lines :
query.send(handleQueryResponse);
query2.send(handleQueryResponse);
function drawChart() {
var visites = new google.visualization.Query('https://docs.google.com/spreadsheets/d/xxx/gviz/tq?sheet=visites');
var transactions = new google.visualization.Query('https://docs.google.com/spreadsheets/d/xxx/gviz/tq?sheet=transactions');
visites.send(handleQueryResponse);
transactions.send(handleQueryResponse2);
conversion.send(handleQueryResponse3);
rebond.send(handleQueryResponse4);
}
function handleQueryResponse(response) {
var options = {
pointSize: 4,
title: '',
}
var data = response.getDataTable();
var chart = new google.visualization.LineChart(document.getElementById('visites'));
chart.draw(data, options);
}
function handleQueryResponse2(response) {
var options = {
pointSize: 4,
title: '',
}
var data = response.getDataTable();
var chart2 = new google.visualization.LineChart(document.getElementById('transactions'));
chart2.draw(data, options);
}
Unfortunately I am not a developer, so I am trying to figure out how it works. I have some knowledge about PHP, HTML and CSS but unfortunately none about JavaScript. Below is my current code of Google Charts Data, it's imported by a module and the javascript code is in places inside the PHP file. Here is my code:
$js = "
google.setOnLoadCallback({$funcChart});
function {$funcChart}() {
var data = google.visualization.arrayToDataTable(".json_encode($data).");
var options = ".json_encode($options).";
var chart = new google.visualization.{$chart}(document.getElementById('{$container}'));
chart.draw(data, options);
}";
if(strpos($width, '%') !== false) {
JHtml::_('JABehavior.jquery');
$js .= "
jQuery(document).ready(function () {
jQuery(window).resize(function(){
{$funcChart}();
});
});
";
}
$doc = JFactory::getDocument();
$doc->addScriptDeclaration($js);
require JModuleHelper::getLayoutPath($module->module, $params->get('layout', 'default'));
}
How do I add a responsive function into the above code? The current chart looks weird on my page; http://goo.gl/v1GVWk
If you open the page and scroll to the "Trekking Map" tab then you will see the chart, but it looks very bad.
Try Using Following Code
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(initChartExpertBottom);
$(window).on("resize", function (event) {
initChartExpertBottom();
});
function initChartExpertBottom() {
var options = {
legend:'none',
width: '100%',
height: '100%',
tooltip: { isHtml: true },
chartArea: {left: "3%",top: "3%",height: "94%",width: "94%"},
colors: ['#7CB5EC', '#5C5C61','#16c104'],
pieHole: 0.50,
pieStartAngle: -90,
is3D: false,
pieSliceText: 'none',
};
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
["Hide" , (11+2)] //addition of value of all elements
]);
drawChartExpertBottom(data, options);
}
function drawChartExpertBottom(data, options) {
var tooltip = [
Math.round((11/(11+2))*100) + "%",
Math.round((2/(11+2))*100)+ "%",
"Hiii3",
];
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
var sliceid = 0;
function eventHandler(e){
chart.setSelection([e]);
try {
selection = chart.getSelection();
sliceid = selection[0].row;
}
catch(err) {
;
}
$(".google-visualization-tooltip-item-list li:eq(0)").css("font-weight", "bold");
$(".google-visualization-tooltip-item-list li:eq(1)").html(tooltip[sliceid]).css("font-family", "Arial");
}
google.visualization.events.addListener(chart, 'onmousedown', eventHandler);
google.visualization.events.addListener(chart, 'onmouseover', eventHandler);
chart.draw(data, options);
}
</script>
HTML for above script
<div id="piechart"></div>
Css for above code snippet
<style>
#piechart {
top: 0;
left: 0;
width:100%;
height:100%;
}
.google-visualization-tooltip{
display:table;
}
g{
cursor:pointer;
}
</style>
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>