polygon is displaying in very smallersize - javascript

I am drawing polygon from existing lonlats. But it is showing in very very smaller size.
Code is as follows,
for(var i in coordinates) {
point = new OpenLayers.Geometry.Point(coordinates.lon,coordinates.lat);
point.transform(new OpenLayers.projection("EPSG:4326"),map.getProjectionObject());
points.push(point);
}
points.push(points[0]);
var linearRing = new OpenLayers.Geometry.LinearRing(points);
var polygonFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null,{strokeColor:"black",
fillColor:"orange",sides:4});
newLayer.addFeatures([polygonFeature]);
newLayer.redraw(true);
But it is displaying in very very small size .
How to show in bigger size? Any help?

The point.transform() not change point object itself, it returns new point,so:
also here is no index (i) used in loop, plus here was syntax error (new OpenLayers.projection should be new OpenLayers.Projection
for(var i in coordinates) {
point = new OpenLayers.Geometry.Point(coordinates[i].lon,coordinates[i].lat);
points.push(
point.transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
)
);
}
points.push(points[0]);
var linearRing = new OpenLayers.Geometry.LinearRing(points);
var polygonFeature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Polygon([linearRing]),null,{
strokeColor:"black",
fillColor:"orange",
});
newLayer.addFeatures([polygonFeature]);
newLayer.redraw(true);
working sample - note a pretty big orange rectangle in africa

Related

Open Layer 3 Animation

i want to animate a marker in Ol3. I used this example from Ol.
The Animation works but with a little bug an i dont know how to fix it.
//main animating loop
var moveFeature = function(event) {
var vectorContext = event.vectorContext;
var frameState = event.frameState;
if (animating) {
var elapsedTime = frameState.time - now;
var now1 = new Date().getTime();
if((now1 - lastTime) > 100){
// stop if end reached
if(curIndex >= coordinates.length){
stopAnimation(true);
requestData(true);
// console.log(" end ");
return;
}
var newPoint = coordinates[curIndex];
var lastP = newPoint;
if(curIndex>=1)
lastP = coordinates[curIndex-1];
if(newPoint !== null & typeof newPoint != " undefined "){
curPoint = ol.proj.fromLonLat(newPoint);
lastCourse = course;
// calculate azimuth between two coordinates
course = calcBearing(lastP,newPoint);
lastTime = now1;
}
curIndex++;
lastTime = now1;
}
//every time render marker position ?? needed ? or only when new one
geoMarker.getGeometry().setCoordinates(curPoint);
//styles.geoMarker.getImage().setRotation(course); //rotates the feature
debugger;
lastCourse = course;
vectorContext.drawFeature(geoMarker, styles.geoMarker);
// do we need follow the bus due to rendering out of current extend =
calcExtend();
}
// tell OL3 to continue the postcompose animation
map.render();
};
I draw the new pos of the marger with vectorContext.drawFeature(geoMarker, styles.geoMarker);
Every time the new position is plotted the vectorlayer is new generated. I dont know why.
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [geoMarker]
//features: [pointFeature]
}),
style: function(feature) {
// hide geoMarker if animation is active
if (animating && feature.get('type') === 'geoMarker') {
// TODOBug
return styles[feature.get('type')];
}
return styles[feature.get('type')];
}
});
With this example above i get the following problem on the map. If the map is clicked, the marker duplicates, one marker stays at the old position and the other one is moving forwoard. Thats a problem.
When i change the code of the vectorlayer like this.
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [geoMarker]
//features: [pointFeature]
}),
style: function(feature) {
// hide geoMarker if animation is active
if (animating && feature.get('type') === 'geoMarker') {
debugger;
console.log("return null")
// TODOBug
return null;
}
return styles[feature.get('type')];
}
});
The problem with the duplicate marker is solved but then the marker isnt clickable while the animation is in progess.
The Question is: How can i achieve that the marker doesen´t duplicates and is clickable while animating???

AngularJS id attribute in the included HTML template

In AngularJS, the id attribute from my HTML Template isn't recognized by my javascript.
For example :
index.html file :
<div ng-controller="SubwayMapController">
<div subway-map></div>
</div>
scripts.js file :
app.directive('subwayMap', function () {
return {
templateUrl: 'Views/subway-map.html'
};
});
map = new OpenLayers.Map("basicMap");
var mapnik = new OpenLayers.Layer.OSM();
var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position = new OpenLayers.LonLat(2.35,48.85).transform( fromProjection, toProjection); //Paris
var zoom = 12;
map.addLayer(mapnik);
map.setCenter(position, zoom );
subway-map.html file :
<div id="basicMap"></div>
When I open index page, I expect the map from Openstreetmap to be displayed but nothing happens.
Try setting up the map in the link() function of the directive. Plus, it looks like you can Map.render() using a DOMElement instead of needing an ID.
app.directive('subwayMap', function () {
return {
templateUrl: 'Views/subway-map.html',
link: function(scope, element) {
var map = new OpenLayers.Map();
var mapnik = new OpenLayers.Layer.OSM();
var fromProjection = new OpenLayers.Projection("EPSG:4326");
var toProjection = new OpenLayers.Projection("EPSG:900913");
var position = new OpenLayers.LonLat(2.35,48.85)
.transform(fromProjection, toProjection);
var zoom = 12;
map.addLayer(mapnik);
map.setCenter(position, zoom );
map.render(element[0]);
}
};
});
put map access code in setTimeout. You are trying to access the map immediately . Angular ain't done with map rendering yet , so setTimeout is the solution.
$timeout(function(){
map = new OpenLayers.Map("basicMap");
var mapnik = new OpenLayers.Layer.OSM();
var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position = new OpenLayers.LonLat(2.35,48.85).transform( fromProjection, toProjection); //Paris
var zoom = 12;
map.addLayer(mapnik);
map.setCenter(position, zoom );
},10);

Changing OpenLayers marker icon

I have a problem with OpenLayers. If I want to change the icon of some marker on the fly (for instance, to paint the marker with another color to indicate a status change), the marker starts behaving buggy, not showing in the proper place and even leaving semi-randomly located copies of itself, noticeable when zooming the map in or out.
I already realized that the problem happens when I reassign the marker.icon attribute, from some pre-loaded icon images which work fine otherwise. I have tried both with and without using icon.clone() to redraw.
Here's a full but simplified example which moves the marker randomly and should modify its icon too. If you comment out the "troublesome code" snippet, it works well, except for the icon change:
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>Mapa</TITLE>
<SCRIPT language="javascript" type="text/javascript" src="OpenLayers.js"></SCRIPT>
<SCRIPT language="javascript" type="text/javascript">
var vMapa;
var prj0 = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var prj1 = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var vLon = 12.568142;
var vLat = 55.676320;
var vTimer = null;
var vCont = 0;
</SCRIPT>
</HEAD>
<BODY onClose="vTimer = null; vLon = null; vLat = null;">
<DIV id="demoMap" style="height: 700px; width: 1000px;"></DIV><DIV id="Contador">0</DIV>
<SCRIPT>
var options = {
controls: [
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar(),
]
};
vMapa = new OpenLayers.Map("demoMap", options);
vMapa.addLayer(new OpenLayers.Layer.OSM());
vMapa.setCenter(new OpenLayers.LonLat(vLon, vLat).transform(prj0, prj1), 15, false, false);
var Navigation = new OpenLayers.Control.Navigation( { defaultDblClick: function(event) { return; } } );
vMapa.addControl(Navigation);
var markers = new OpenLayers.Layer.Markers("Markers");
vMapa.addLayer(markers);
var size = new OpenLayers.Size(12, 12);
var offset = new OpenLayers.Pixel(-6, -6);
var iconOff = new OpenLayers.Icon('img/CircOff.png', size, offset);
var iconOn = new OpenLayers.Icon('img/CircOn.png', size, offset);
var marker = new OpenLayers.Marker(new OpenLayers.LonLat(vLon, vLat).transform(prj0, prj1), iconOff.clone());
marker.setOpacity(1.0);
marker.events.register('mousedown', marker, function(evt) { vMapa.panTo(marker.lonlat); OpenLayers.Event.stop(evt); });
marker.pfInfo = 'Vel: 0.0 km/h';
markers.addMarker(marker);
vTimer = setTimeout('TimerEvent()', 1000);
function TimerEvent() {
vLon += ((Math.random() - 0.5) / 500);
vLat += ((Math.random() - 0.5) / 500);
// ------- Troublesome code -------
var ixIcon = Math.round(Math.random());
if (ixIcon == 0) {
marker.icon = iconOff.clone();
} else {
marker.icon = iconOn.clone();
}
// --------------------------------
var newLonLat = new OpenLayers.LonLat(vLon, vLat).transform(prj0, prj1);
var newPx = marker.map.getLayerPxFromViewPortPx(marker.map.getPixelFromLonLat(newLonLat));
marker.moveTo(newPx);
marker.draw();
vCont ++;
document.getElementById('Contador').innerHTML = vCont;
vTimer = setTimeout('TimerEvent()', 1000);
}
</SCRIPT>
</BODY>
</HTML>
Thanks a lot in advance for your suggestions.
I never use Marker to create markers.
I create a Vector layer, and add Point objects. Then style these Points.
This works much better and has more functionality.
You can create a restful web service which can return an SVG as a string. The parameters passed would tell the service what has to change on the icon. The service would read in a template SVG change it appropriately and return it.

Flame is not showing in THREE.js World

I am making a flame using the THREE.js and spark.js, but when I render the world I can't see the flame and the world is empty. I saw the console for the error but there is no error regarding this. I tried a lot but can't find out the actual error. Here is the code.
threexSparks = new THREEx.Sparks({
maxParticles : 400,
counter : new SPARKS.SteadyCounter(300)
});
//threexSparks.position.x = 1000;
// setup the emitter
//var emitter = threexSparks.emitter();
var counter = new SPARKS.SteadyCounter(500);
var emitter = new SPARKS.Emitter(counter);
var initColorSize = function() {
this.initialize = function(emitter, particle) {
particle.target.color().setHSV(0.3, 0.9, 0.4);
particle.target.size(150);
};
};
emitter.addInitializer(new initColorSize());
emitter.addInitializer(new SPARKS.Position(new SPARKS.PointZone(new THREE.Vector3(1000, 0, 0))));
emitter.addInitializer(new SPARKS.Lifetime(0, 0.8));
emitter.addInitializer(new SPARKS.Velocity(new SPARKS.PointZone(new THREE.Vector3(0, 250, 00))));
emitter.addAction(new SPARKS.Age());
emitter.addAction(new SPARKS.Move());
emitter.addAction(new SPARKS.RandomDrift(1000, 0, 1000));
emitter.addAction(new SPARKS.Accelerate(0, -200, 0));
Thanks
Tere is strange problems with particles and WebGL render. It will be good if you're using CanvasRender. But for WebGL not.
Also in your code you forgot about creating threejs objects for particles. Sparks.js allows only interface for particles. But you need to create particles itself.
You can look at my jsfiddle example. there I use modified version of sparks.js library. Changes just to be able to override VectorPool behaviour.
http://jsfiddle.net/YeJ4X/35/
Main part there is:
var particleCount = 1800,
particles = new THREE.Geometry(), //store particle vertices
pMaterial = new THREE.ParticleBasicMaterial({
size: 10,
map: txture, //in jsfiddle i create texture from canvas
transparent: true
});
var particleSystem = new THREE.ParticleSystem(particles, pMaterial); //threejs particle system
//initialize our particles (and set that are dirty). sparkjs initialize it later for us
for(var p = 0; p < particleCount; p++) {
v = new THREE.Vector3(numMax,numMax,numMax);
v.isDirty=true;
particles.vertices.push(v);
}
SPARKS.VectorPool.__pools = particles.vertices; //initialize vectors pool
And there is my new vector pool for sparksjs
SPARKS.VectorPool = {
__pools: [],
get: function() {
var ret = _.find(this.__pools, function(v){return v.isDirty});
ret.isDirty=false;
return ret;
},
release: function(v) {
v.isDirty=true;
v.set(numMax,numMax,numMax);
}
};
Of course you must care about count of partices that are used in sparks.js and precreated by hands.
My sparkjs fork is here: https://github.com/elephanter/sparks.js there I fix problem with lastest tweenjs and add other little changes I described before.

OpenLayers => feature is null

This is my GeoJSON result. PasteBin
But when I load it, the result I get in firebug is feature is null. Why's that, are there any errors in my result? The coords in the JSON is written in projection WGS84, and in the code I also have set the externalProjection as WGS84. So why do I get the return "feature is null"?
The code I use to manage my map is :
$(document).ready(function() {
var wgs84 = new OpenLayers.Projection('EPSG:4326');
var layer = null;
var map = new OpenLayers.Map('map',{projection: wgs84});
layer = new OpenLayers.Layer.OSM( "Simple OSM Map");
var baseProjection = layer.projection;
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(10,10), 4);
map.events.register("moveend", null, function(){
if(map.zoom == 10)
{
var bounds = map.getExtent();
console.log(bounds);
var ne = new OpenLayers.LonLat(bounds.right,bounds.top).transform(map.getProjectionObject(),wgs84);
var sw = new OpenLayers.LonLat(bounds.left,bounds.bottom).transform(map.getProjectionObject(),wgs84);
var vectorLayer = new OpenLayers.Layer.Vector();
map.addLayer(vectorLayer);
$.getJSON('ajax.php?a=markers&type=json&sw=('+sw.lon+','+sw.lat+')&ne=('+ne.lon+','+ne.lat+')',function(data){
//$.getJSON('test.json',function(data){
var geojson_format = new OpenLayers.Format.GeoJSON({
'externalProjection': wgs84,
'internalProjection': baseProjection
});
vectorLayer.addFeatures(geojson_format.read(data));
});
}
});
});
Your sample OpenLayer code is working correctly, the problem is in your GeoJSON: you misspelled coordinates as "coordninates"

Categories

Resources