Open layers label not working - javascript

I've been trying to get the openlayers label feature to work and produced the following example:
<html>
<head>
<title>OpenLayers Example</title>
<script src="http://openlayers.org/api/OpenLayers.js"></script>
</head>
<body>
<div style="width:100%; height:100%" id="map"></div>
<script>
var map = new OpenLayers.Map('map');
var wms = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: 'basic'} );
map.addLayer(wms);
// Default polygon style
var polygonStyle =
OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
polygonStyle.strokeColor = "#800000";
polygonStyle.fillColor = "#800080";
polygonStyle.fillOpacity = 0.2;
polygonStyle.strokeWidth = 1;
polygonStyle.label = "Label:${label}";
polygonStyle.labelOutlineColor = "white";
polygonStyle.labelOutlineWidth = 3;
var smap = new OpenLayers.StyleMap({"default": polygonStyle});
var veclayer = new OpenLayers.Layer.Vector("Survey Locations", {"styleMap": smap});
map.addLayer(veclayer);
var data = {"type":"Polygon","coordinates":[[
[-2.07362131225228,52.0329916851734],
[-2.07096056091493,52.0228522264397],
[-2.05061868774548,52.0156687188299],
[-2.04280809509186,52.0210036398637],
[-2.02804521667506,52.0231163039992],
[-2.01748804200037,52.0300345805213],
[-2.01645807373352,52.0464545997404],
[-2.02589944946666,52.0529998067114],
[-2.04194978821027,52.0554276235705],
[-2.06023172485491,52.0455044093648],
[-2.07362131225228,52.0329916851734]]]};
var gson = new OpenLayers.Format.GeoJSON();
var GEO = gson.read(data, "Geometry");
var EPSG4326 = new OpenLayers.Projection("EPSG:4326");
GEO = GEO.transform(EPSG4326, map.getProjectionObject());
var locname="First label";
var FEA = new OpenLayers.Feature.Vector(GEO, {"label":locname}, polygonStyle);
veclayer.addFeatures([FEA]);
map.zoomToExtent(GEO.getBounds(),false);
data= {"type":"Polygon","coordinates":[[[-2.04514962074064,52.0403793945411],
[-2.03057040393828,52.0403841112724],
[-2.03057659173109,52.0493747022699],
[-2.04515873420745,52.049369984023],
[-2.04514962074064,52.0403793945411]]]}
var GEO = gson.read(data, "Geometry");
var EPSG4326 = new OpenLayers.Projection("EPSG:4326");
GEO = GEO.transform(EPSG4326, map.getProjectionObject());
var locname="Second label";
var FEA = new OpenLayers.Feature.Vector(GEO, {"label":locname}, polygonStyle);
veclayer.addFeatures([FEA]);
</script>
</body>
</html>
The code works but the label on the polygons displays as Label:${Label} rather than interpreting the variable to read Label: First label etc.
When this is integrated into a larger application the first label is not interpreted correctly but the second is. I suspect that it may be a layer initialisation problem but have no idea how to get over this.
Any help would be appreciated!!

Have you tried to add attributes as object after declaring the feature for example:
FEA.attributes = {
label:locname
}
It worked this way see, the changes below:
<html>
<head>
<title>OpenLayers Example</title>
<script src="http://openlayers.org/api/OpenLayers.js"></script>
</head>
<body>
<div style="width:100%; height:100%" id="map"></div>
<script>
var map = new OpenLayers.Map('map');
var wms = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: 'basic'} );
map.addLayer(wms);
// Default polygon style
var polygonStyle =
OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
polygonStyle.strokeColor = "#800000";
polygonStyle.fillColor = "#800080";
polygonStyle.fillOpacity = 0.2;
polygonStyle.strokeWidth = 1;
polygonStyle.label = "Label:${label}";
polygonStyle.labelOutlineColor = "white";
polygonStyle.labelOutlineWidth = 3;
var smap = new OpenLayers.StyleMap({"default": polygonStyle});
var veclayer = new OpenLayers.Layer.Vector("Survey Locations", {"styleMap": smap});
map.addLayer(veclayer);
var data = {"type":"Polygon","coordinates":[[
[-2.07362131225228,52.0329916851734],
[-2.07096056091493,52.0228522264397],
[-2.05061868774548,52.0156687188299],
[-2.04280809509186,52.0210036398637],
[-2.02804521667506,52.0231163039992],
[-2.01748804200037,52.0300345805213],
[-2.01645807373352,52.0464545997404],
[-2.02589944946666,52.0529998067114],
[-2.04194978821027,52.0554276235705],
[-2.06023172485491,52.0455044093648],
[-2.07362131225228,52.0329916851734]]]};
var gson = new OpenLayers.Format.GeoJSON();
var GEO = gson.read(data, "Geometry");
var EPSG4326 = new OpenLayers.Projection("EPSG:4326");
GEO = GEO.transform(EPSG4326, map.getProjectionObject());
var locname="First label";
var FEA = new OpenLayers.Feature.Vector(GEO);
FEA.attributes = {
label:locname
}
veclayer.addFeatures([FEA]);
map.zoomToExtent(GEO.getBounds(),false);
data= {"type":"Polygon","coordinates":[[[-2.04514962074064,52.0403793945411],
[-2.03057040393828,52.0403841112724],
[-2.03057659173109,52.0493747022699],
[-2.04515873420745,52.049369984023],
[-2.04514962074064,52.0403793945411]]]}
var GEO = gson.read(data, "Geometry");
var EPSG4326 = new OpenLayers.Projection("EPSG:4326");
GEO = GEO.transform(EPSG4326, map.getProjectionObject());
var locname="Second label";
var FEA = new OpenLayers.Feature.Vector(GEO);
FEA.attributes = {
label: locname
}
veclayer.addFeatures([FEA]);
</script>
</body>
</html>

Related

How to pass user input and custom function creation in amchart script?

I am using am4chart script to plot map and want to use user given geo-coordinate points. I am taking inputs like:
Latitude: <input type="number" name="a" id="a" ><br>
Longitude: <input type="number" name="b" id="b"><br>
<button onclick="point(document.getElementById('a').value,document.getElementById('b').value)">Add</button>
I want to define my function in amchart given script like:
function point(a,b) {
console.log(parseFloat(a));
console.log(parseFloat(b));
var marker = imageSeries.mapImages.create();
<!-- Try to put lat long -->
marker.latitude = parseFloat(a);
marker.longitude = parseFloat(b);
}
But I got error:
Uncaught ReferenceError: point is not defined
at HTMLButtonElement.onclick
How can I pass points data to show marker in the map?
Here is the full script for map plot:
<!-- Chart code -->
<script>
am4core.ready(function() {
// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end
var continents = {
"AF": 0,
"AN": 1,
"AS": 2,
"EU": 3,
"NA": 4,
"OC": 5,
"SA": 6
}
// Create map instance
var chart = am4core.create("chartdiv", am4maps.MapChart);
chart.projection = new am4maps.projections.Miller();
// Create map polygon series for world map
var worldSeries = chart.series.push(new am4maps.MapPolygonSeries());
worldSeries.useGeodata = true;
worldSeries.geodata = am4geodata_worldLow;
worldSeries.exclude = ["AQ"];
var worldPolygon = worldSeries.mapPolygons.template;
<!--worldPolygon.tooltipText = "{name}";-->
worldPolygon.nonScalingStroke = true;
worldPolygon.strokeOpacity = 0.5;
worldPolygon.fill = am4core.color("#eee");
worldPolygon.propertyFields.fill = "color";
var hs = worldPolygon.states.create("hover");
hs.properties.fill = chart.colors.getIndex(9);
// Create country specific series (but hide it for now)
var countrySeries = chart.series.push(new am4maps.MapPolygonSeries());
countrySeries.useGeodata = true;
countrySeries.hide();
countrySeries.geodataSource.events.on("done", function(ev) {
worldSeries.hide();
countrySeries.show();
});
var countryPolygon = countrySeries.mapPolygons.template;
<!--countryPolygon.tooltipText = "{name}";-->
countryPolygon.nonScalingStroke = true;
countryPolygon.strokeOpacity = 0.5;
countryPolygon.fill = am4core.color("#eee");
var hs = countryPolygon.states.create("hover");
hs.properties.fill = chart.colors.getIndex(9);
// Set up click events
worldPolygon.events.on("hit", function(ev) {
ev.target.series.chart.zoomToMapObject(ev.target);
var map = ev.target.dataItem.dataContext.map;
if (map) {
ev.target.isHover = false;
countrySeries.geodataSource.url = "https://www.amcharts.com/lib/4/geodata/json/" + map + ".json";
countrySeries.geodataSource.load();
}
});
// Set up data for countries
var data = [];
for(var id in am4geodata_data_countries2) {
if (am4geodata_data_countries2.hasOwnProperty(id)) {
var country = am4geodata_data_countries2[id];
if (country.maps.length) {
data.push({
id: id,
color: chart.colors.getIndex(continents[country.continent_code]),
map: country.maps[0]
});
}
}
}
worldSeries.data = data;
// Zoom control
chart.zoomControl = new am4maps.ZoomControl();
// Set initial zoom
chart.homeZoomLevel = 4;
chart.homeGeoPoint = {
latitude: 28.644800,
longitude: 77.216721
};
<!--!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Marker !!!!!!!!!!!!!!!!!!!!!!-->
// Define marker path
var targetSVG = "M9,0C4.029,0,0,4.029,0,9s4.029,9,9,9s9-4.029,9-9S13.971,0,9,0z M9,15.93 c-3.83,0-6.93-3.1-6.93-6.93S5.17,2.07,9,2.07s6.93,3.1,6.93,6.93S12.83,15.93,9,15.93 M12.5,9c0,1.933-1.567,3.5-3.5,3.5S5.5,10.933,5.5,9S7.067,5.5,9,5.5 S12.5,7.067,12.5,9z";
<!--!!!!!!!!!!!!!!!! Retrieving coordinates of a click !!!!!!!!!!!!-->
chart.seriesContainer.events.on("hit", function(ev) {
console.log(chart.svgPointToGeo(ev.svgPoint));
var coords = chart.svgPointToGeo(ev.svgPoint);
var marker = imageSeries.mapImages.create();
<!-- Try to put lat long -->
marker.latitude = coords.latitude;
marker.longitude = coords.longitude;
console.log(document.getElementById('lat').value);
});
function point(a,b) {
console.log(parseFloat(a));
console.log(parseFloat(b));
<!-- Try to put lat long -->
marker.latitude = parseFloat(a);
marker.longitude = parseFloat(b);
}
<!--!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!-->
// Add images
var imageSeries = chart.series.push(new am4maps.MapImageSeries());
var imageTemplate = imageSeries.mapImages.template;
imageTemplate.tooltipText = "{title}";
imageTemplate.nonScaling = true;
var marker = imageTemplate.createChild(am4core.Sprite);
marker.path = targetSVG;
marker.horizontalCenter = "middle";
marker.verticalCenter = "middle";
marker.scale = 0.7;
<!--marker.fill = interfaceColors.getFor("alternativeBackground");-->
imageTemplate.propertyFields.latitude = "latitude";
imageTemplate.propertyFields.longitude = "longitude";
<!--imageSeries.data = [ {-->
<!-- "title": "Delhi",-->
<!-- 'latitude': 28.644800,-->
<!-- 'longitude': 77.216721,-->
<!-- "scale": 1-->
<!-- }, {-->
<!-- "title": "Kiev",-->
<!-- "latitude": a,-->
<!-- "longitude": b,-->
<!-- }];-->
var homeButton = new am4core.Button();
homeButton.events.on("hit", function() {
worldSeries.show();
countrySeries.hide();
chart.goHome();
});
homeButton.icon = new am4core.Sprite();
homeButton.padding(7, 5, 7, 5);
homeButton.width = 30;
homeButton.icon.path = "M16,8 L14,8 L14,16 L10,16 L10,10 L6,10 L6,16 L2,16 L2,8 L0,8 L8,0 L16,8 Z M16,8";
homeButton.marginBottom = 10;
homeButton.parent = chart.zoomControl;
homeButton.insertBefore(chart.zoomControl.plusButton);
}); // end am4core.ready()
</script>

Create chart in a new Tab using Angular Js

I have a function that creates a chart in a new tab. I have done this in javascript. How should this be converted into AngularJs.
function OpenWin() {
var w = window.open();
w.document.open();
w.document.write('<div id="container" style="width:100%; height:400px;"></div>');
w.document.write('<select id="type" onchange="ChartFunc(this.value)"><option value="line">line</option><option value="column">column</option> <option value="area">area</option><option value="bar">bar</option></select>');
var scriptHead = w.document.createElement("SCRIPT");
var scriptHead1 = w.document.createElement("SCRIPT");
var link = "http://code.highcharts.com/highcharts.js";
var link1 = "http://code.highcharts.com/modules/exporting.js";
scriptHead.onload = function() {
var script = w.document.createElement("SCRIPT");
w.document.body.appendChild(script);
var js = w.document.createTextNode('var a = localStorage.getItem("ImportOptions"); var jsona = JSON.parse(a); var chart = new Highcharts.Chart(jsona);function ChartFunc(value){ console.log(value); jsona.chart.type = value;var chart = new Highcharts.Chart(jsona); }');
script.appendChild(js);
w.document.close();
scriptHead1.src = link1;
w.document.head.appendChild(scriptHead1);
}
scriptHead.src = link;
w.document.head.appendChild(scriptHead);
}

Creating a reusable function for loaders in three.js

I am trying to find a way how to create a reusable function that prevents me from repeating the same loader code over and over again. An example can be seen below:
one = new THREE.Group();
var loader1 = new THREE.TextureLoader();
loader1.crossOrigin = '';
loader1.load('',
function (texture) {
this.geo = new THREE.BoxGeometry(10,10,10);
this.mat = new THREE.MeshBasicMaterial({color:'white'});
this.mesh = new THREE.Mesh(this.geo, this.mat);
one.add(mesh)
}
);
twp = new THREE.Group();
var loader2 = new THREE.TextureLoader();
loader2.crossOrigin = '';
loader2.load('',
function (texture) {
this.geo = new THREE.BoxGeometry(10,10,10);
this.mat = new THREE.MeshBasicMaterial({color:'white'});
this.mesh = new THREE.Mesh(this.geo, this.mat);
two.add(mesh)
}
);
My attempt was as follows:
example = new THREE.Group();
function reuse(obj) {
this.loader = new THREE.TextureLoader();
this.loader.crossOrigin = '';
this.loader.load('',
function (texture) {
this.geo = new THREE.BoxGeometry(10,10,10);
this.mat = new THREE.MeshBasicMaterial({color:'white'});
this.mesh = new THREE.Mesh(this.geo, this.mat);
obj.name.add(mesh)
}
)
};
var test = new reuse({name: 'example'});
I also tried pushing the mesh in an array within the function:
arr.push(mesh);
arr.mesh[0].position.x
etc.
I also tried returning it.
What exactly is the best and working method to avoid such disaster?
when dealing with duplicate code the most common and easiest way is to create a simple function
example with your code:
function getTexturedCube(path){
var geometry = new THREE.BoxGeometry(10,10,10);
var loader = new THREE.TextureLoader();
//you dont have to put onLoad function in,
//the texture returned will automatically update when it is loaded
var texture = loader.load(path);
var material = new THREE.MeshBasicMaterial({map:texture});
return new THREE.Mesh(geometry, material)
}
var group = new THREE.Group();
var cube1 = getTexturedCube("/path/to/image");
var cube2 = getTexturedCube("/path/to/other/image");
group.add(cube1);
group.add(cube2);
var anotherGroup = new THREE.Group();
var cube3 = getTexturedCube("/path/to/yet/another/image")
anotherGroup.add(cube3);
you can also pass the function a reference to your group and make it push the object into it
function addTexturedCube(path, object){
var geometry = new THREE.BoxGeometry(10,10,10);
var loader = new THREE.TextureLoader();
var texture = loader.load(path);
var material = new THREE.MeshBasicMaterial({map:texture});
object.add(new THREE.Mesh(geometry, material));
}
var group = new THREE.Group();
addTexturedCube("/path/to/image", group);
addTexturedCube("/path/to/other/image", group);

How to resolve Uncaught TypeError: object is not a function?

I am getting this error in my javascript code. It worked fine when I was working on the chart and maps separately. But the moment I integrated these two it stopped working.
<html>
<head>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load('visualization', '1', {'packages': ['geomap']});
google.setOnLoadCallback(drawMap);
var test;
function drawMap() {
var test1 = {{pie2008|safe}}
var test2 = {{pie2009|safe}}
var test3 = {{pie2010|safe}}
console.log(test1);
console.log(test2);
console.log(test3);
}
function drawMap2008() {
console.log("In draw map function");
var data = google.visualization.arrayToDataTable({{data2008|safe}});
var options = {};
options['region'] = 'US'
options['dataMode'] = 'regions';
var container = document.getElementById('map_canvas');
var geomap = new google.visualization.GeoMap(container);
console.log(data);
geomap.draw(data, options);
}
function drawMap2009() {
console.log("In draw map function");
var data = google.visualization.arrayToDataTable({{data2009|safe}});
var options = {};
options['region'] = 'US'
options['dataMode'] = 'regions';
var container = document.getElementById('map_canvas');
var geomap = new google.visualization.GeoMap(container);
console.log(data);
geomap.draw(data, options);
}
function drawMap2010() {
console.log("In draw map function");
var data = google.visualization.arrayToDataTable({{data2010|safe}});
var options = {};
options['region'] = 'US'
options['dataMode'] = 'regions';
var container = document.getElementById('map_canvas');
var geomap = new google.visualization.GeoMap(container);
console.log(data);
geomap.draw(data, options);
}
function drawChart2008() {
var data = google.visualization.arrayToDataTable({{pie2008|safe}});
var options = {
title: 'Maximum Facebook users for 2008',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
function drawChart2009() {
console.log("In draw map function");
var data = google.visualization.arrayToDataTable({{pie2009|safe}});
var options = {
title: 'Maximum Facebook users for 2009',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
function drawChart2010() {
console.log("In draw map function");
var data = google.visualization.arrayToDataTable({{pie2010|safe}});
var options = {
title: 'Maximum Facebook users for 2010',
pieHole: 0.4,
};
var container2 = document.getElementById('donutchart');
var chart = new google.visualization.PieChart(container2);
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="handb">
<h3>No of facebook users per state</h3>
<button id="data2008" onclick = "drawMap2008()">Intensity Map for 2008</button>
<button id="data2009" onclick = "drawMap2009()">Intensity Map for 2009</button>
<button id="data2010" onclick = "drawMap2010()">Intensity Map for 2010</button>
<button id="pie2008" onclick = "drawChart2008()">Pie chart for 2008</button>
<button id="pie2009" onclick = "drawChart2009()">Pie chart for 2009</button>
<button id="pie2010" onclick = "drawChart2010()">Pie chart for 2010</button>
</div>
<div id='map_canvas'></div>
<div id='donutchart'></div>
</body>
</html>
I am not understanding why I am getting this error. I am getting this error in the drawchart2008 function on the line -
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
My suspicion would be that chart.draw(data, options); is not actually a function (.draw() is not a method on the type chart).
Just because .draw() exists on geomap.draw(data, options); does not mean that it does for chart.

problems with a popup in openlayes

I need to make permanent popup but only managed to make it show when a mouse event, i found an example but nothing to adapt achievement: http://openlayers.org/dev/examples/osm-marker-popup.html
anyone can help me to make permanent the popup, Thanks.
var mapa;
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
OpenLayers.ImgPath = "/openlayers/img/"
mapa = new OpenLayers.Map('map',{
controls: [
new OpenLayers.Control.Attribution(),
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar(),
],
theme: null
});
var osm = new OpenLayers.Layer.OSM( " Open Street Map" );
var markers = new OpenLayers.Layer.Markers( "Ruta" );
$.each(info, function(i, data){
var size = new OpenLayers.Size(21,25);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon('/openlayers/img/data.png',size,offset);
var lonlat = new OpenLayers.LonLat(parseFloat(data.long),parseFloat(data.lat));
var proj_1 = new OpenLayers.Projection("EPSG:4326");
var proj_2 = new OpenLayers.Projection("EPSG:900913");
var EPSG = lonlat.transform(proj_1,proj_2);
var marker = new OpenLayers.Marker(EPSG, icon);
markers.addMarker(marker);
// popup
marker.events.register("click", marker, function(e){
var popup = new OpenLayers.Popup.FramedCloud(data.idunidad,
marker.lonlat,
new OpenLayers.Size(200,200),
'<p>info in the popup, mouse event</p>',
null,true);
popup.idunidad = data.idunidad;
mapa.addPopup(popup);
arrPopup.push(popup);
});
});
var lonlat = new OpenLayers.LonLat(-74.075833,4.598056);
var proj_1 = new OpenLayers.Projection("EPSG:4326");
var proj_2 = new OpenLayers.Projection("EPSG:900913");
var centrar = lonlat.transform(proj_1,proj_2);
mapa.addLayers([osm,markers]);
mapa.setCenter(centrar, 5);
mapa.addControl(new OpenLayers.Control.LayerSwitcher());
Why not use vector layers, you know this example?
http://openlayers.org/dev/examples/dynamic-text-layer.html

Categories

Resources