How to draw a linestring from POINT(".........")? - javascript

I got this Openlayer Question.
Im trying to get a bunch of points from some objects. Which i believe shouldnt be hard.
Im am passing the st_astext to the WKT reader to create a Openlayers.Geometry.Point() Feature to add to the initial layer that will hold all of the lines. But that doesnt seem to work. Can anyone see what im doing wrong?
//Routes for each bridge?
vesselPosition = new OpenLayers.Layer.Vector('Vessels');
var wkt = new OpenLayers.Format.WKT();
$.ajax({
url: "/ajax/getPositions",
dataType: 'json',
success: function(result) {
for (var reportID in result) {
//Store the object at hand.
var data = result[reportID];
//Get all the positions and print them onto the vesselpoisition layer.
var positions = data.positions;
var listOfPoints = new Array();
for (var index in positions) {
var positionData = positions[index];
var point= wkt.read(positionData.st_astext);
listOfPoints.push(point.geometry);
}
var pointmap = new OpenLayers.Geometry.LineString({points:listOfPoints});
vesselPosition.addFeatures(pointmap);
};
}
});

OpenLayers.Geometry.LineString expects array of points for parameter, not object:
http://dev.openlayers.org/docs/files/OpenLayers/Geometry/LineString-js.html#OpenLayers.Geometry.LineString.OpenLayers.Geometry.LineString
Answer: Projection issue:
point.geometry.transform(
new OpenLayers.Projection("EPSG:4326"),
new OpenLayers.Projection("EPSG:900913")
);
So try
var pointmap = new OpenLayers.Geometry.LineString(listOfPoints);
Also pay attention for
vesselPosition.addFeatures(pointmap);
addFeatures() expects feature, not geometry for parameter. Use:
vesselPosition.addFeatures(new OpenLayers.Feature.Vector(pointmap));
For testing purposes, you may draw individual points to map:
var point= wkt.read(positionData.st_astext);
vesselPosition.addFeatures(point);
Also, check vesselPosition.features.length to determine, whether there are any features.

Related

Leaflet: showing dynamic polylines together on a map using layers

I'm working on a task of showing all polylines(of different colours) on my map using leaflet. I'm getting all my dynamic polylines' latitudes and longitudes with their colours but when I merge it using layers, it just takes the last polyline and shows it.
I think I'm making some mistake in layering it. Can someone recommend the correct way to layer polylines in leaflets?
Here's a sample of the code where this is happening -
let newColour = this.returnMapColor(moment(startDate).day());
var layerGroups = {}
console.log("colour", newColour, startDate );
let range = this.props.history.filter((v) => { return moment(v.time).format("YYYY-MM-DD") == moment(startDate).format("YYYY-MM-DD") });
startDate = moment(startDate).add(1, 'days');
range.map((row)=> {
positions.push([row.latitude,row.longitude,row.sp] )
});
if(this.props.map){
const leafletMap = this.props.map.leafletElement;
this.hotlineLayer = L.layerGroup(L.polyline(positions, {color: newColour})).addTo(leafletMap);
}
++i;
A polyline requires at least two sets of lat, longs. Could you point out where in your code are you forming polylines?
In your code, the range.map the operation will only lead to creating an array of positions. And hence, your code is rendering a single line.
If you intend to create multiple polylines and render them using LayerGroup, I would suggest something in the lines of:
var latlngs1 = [
[45.51, -122.68,0],
[37.77, -122.43,1],
[34.04, -118.2,2]
];
var latlngs2 = [
[34.04, -118.2,2],
[32.08, -110.5,2]
];
const polyline1 = L.polyline(latlngs1, {color: 'red'})
var polyline2 = L.polyline(latlngs2, {color: 'blue'})
var hotlineLayer = L.layerGroup([polyline1, polyline2]).addTo(map);
Example Code: https://jsfiddle.net/idhruvs/n75omjbd/32/

How to pass in coordinates to LatLng function in Leaflet

I'm trying to figure out how to pass in coordinates to the L.LatLng function in leaflet so that it can map the coordinates.
I can successfully load in the data, and it looks like this:
//This is the structure of the geojson data, as an example
var SanFranciscoData = {"type":"FeatureCollection", "features": [
{"type":"Feature","geometry":{"type":"Point","coordinates":[-96.97593699999999,32.889954000000046]}
//Load in the geojson
d3.json("data/dataPoints.json", function(SFData) {
var SFData = SanFranciscoData.features
})
//pass in coordinates to the L.LatLng leaflet function
SFData.forEach(function(d) {
d.latLong = new L.LatLng(d.features.geometry.coordinates[1],
d.features.geometry.coordinates[0]);
})
I've also tried, as I've seen done in examples:
var coords = SFData.feature.geometry.coordinates;
Both methods above give the same result: the coordinates are undefined. What am I doing wrong? I'm not sure how to access the coordinates array using object notation in order to access the lat / longs.
Ok.. this worked:
SFData.forEach(function(d) {
var coords = d.geometry.coordinates
console.log(coords)
d.latLong = new L.LatLng(coords[1],
coords[0]);
})
Seems as if coordinates needed to be defined withing the .forEach function!

How to clamp GeoJSON data format to terrain in Cesium Sandcastle?

I have terrain view in Cesium Sandcastle and I have loaded roads data in GeoJSON format, they are lines. I want to clamp them on terrain, like this example (in drop-down menu choose "Sample line positions and draw with depth test disabled") -> http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Ground%20Clamping.html&label=Tutorials
In the example, the line you see is defined within code, but I have data (roads) on my PC which is loaded in app. When loaded, roads are flat (under the terrain) and somehow I have to clamp them on terrain but don't know how.
I have tried using the existing code from the example but haven't succeed.
This is my code for now:
//Add terrain
var viewer = new Cesium.Viewer('cesiumContainer');
var cesiumTerrainProviderMeshes = new Cesium.CesiumTerrainProvider({
url : 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
requestWaterMask : true,
requestVertexNormals : true
});
viewer.terrainProvider = cesiumTerrainProviderMeshes;
viewer.scene.globe.depthTestAgainstTerrain = true;
//Load data (roads)
var dataSource = Cesium.GeoJsonDataSource.load('../../SampleData/ceste_rab_okvir.geojson');
viewer.dataSources.add(dataSource);
viewer.zoomTo(dataSource);
I know there is Cesium.GeoJsonDataSource.clampToGround, but as I'm not a developer, I don't understand how to write it in my code.
Does anyone knows how to do it? Or maybe there is another way to clamp roads to terrain?
Thanks in advance.
I've figured it out. It should be written like this:
//Add terrain
var viewer = new Cesium.Viewer('cesiumContainer');
var cesiumTerrainProviderMeshes = new Cesium.CesiumTerrainProvider({
url : 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
requestWaterMask : true,
requestVertexNormals : true
});
viewer.terrainProvider = cesiumTerrainProviderMeshes;
viewer.scene.globe.depthTestAgainstTerrain = true;
//Load data (roads)
Cesium.GeoJsonDataSource.clampToGround = true;
var dataSource = Cesium.GeoJsonDataSource.load('../../SampleData/ceste_rab_okvir.geojson');
viewer.dataSources.add(dataSource);
viewer.zoomTo(dataSource);

Integrate Google Map with Markers from HTTPrequest Javascript

Hi there I am Using appcelerator, and I want to integrate a map with an array of markers I am getting from a HTTPRequest...
I am effing lost, totally lost.
This is how the map looks like:
var mapview = Titanium.Map.createView({
mapType: Titanium.Map.STANDARD_TYPE,
region: {latitude:33.74511, longitude:-84.38993,
latitudeDelta:0.01, longitudeDelta:0.01},
animate:true,
regionFit:true,
userLocation:true,
annotations:[mountainView]
});
And I have the example of 1 marker hardcoded ...
var mountainView = Titanium.Map.createAnnotation({
latitude:37.390749,
longitude:-122.081651,
title:"Appcelerator Headquarters",
subtitle:'Mountain View, CA',
pincolor:Titanium.Map.ANNOTATION_RED,
animate:true,
leftButton: '../images/appcelerator_small.png',
myid:1 // CUSTOM ATTRIBUTE THAT IS PASSED INTO EVENT OBJECTS
});
So yo create the marker and in the annotations section you add it to the map, the thing here is that I am getting the markers from this:
var url = "http://myURLwithMyParameters";
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this function is called when data is returned from the server and available for use
// this.responseText holds the raw text return of the message (used for text/JSON)
var result = this.responseText;
var xml = Ti.XML.parseString(result);
var items = xml.documentElement.getElementsByTagName("marker");
var name = xml.documentElement.getElementsByTagName("name");
var value = xml.documentElement.getElementsByTagName("address");
var data = [];
for (var i=0;i<items.length;i++) {
data.push({
name: items.item[i].getElementsByTagName("name")[0].textContent,
address: items.item[i].getElementsByTagName("address")[0].textContent
})
Does any one know how to integrate this?
I think I must build the map in the same function as the markers, but I've tried several options and haven't found ANY example of this in the web.
Any clue would be very appreciated.
Thank you in advance.
If all you have is an address, you'll need to forward geocode those addresses to get lat/long coordinates. Those coords are required to place annotations on the map. Check the docs at forwardGeocoder(). There's an example in the KitchenSink

open layers LineString not working

Sorry to bother you guys, but I'm stuck with his problem for half a day.
I want to draw poly line in OpenLayers using LineString object, so I've copied the example from documentation. It runs ok but i can't see the line on the screen
Code looks like this
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<script type="text/javascript" src="http://openlayers.org/api/OpenLayers.js"></script>
<script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>
<script src='http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAjpkAC9ePGem0lIq5XcMiuhR_wWLPFku8Ix9i2SXYRVK3e45q1BQUd_beF8dtzKET_EteAjPdGDwqpQ'></script>
<script type="text/javascript">
var map;
var lineLayer ;
var points;
var style;
var polygonFeature
function test()
{
lineLayer = new OpenLayers.Layer.Vector("Line Layer");
style = { strokeColor: '#0000ff',
strokeOpacity: 1,
strokeWidth: 10
};
map.addLayer(lineLayer);
points = new Array();
points[0] =new OpenLayers.LonLat(-2.460181,27.333984 ).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());;
points[1] = new OpenLayers.LonLat(-3.864255,-22.5 ).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());;
var linear_ring = new OpenLayers.Geometry.LinearRing(points);
polygonFeature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Polygon([linear_ring]), null, style);
lineLayer.addFeatures([polygonFeature]);
alert("1");
}
function initialize()
{
map = new OpenLayers.Map ("map_canvas", {
controls:[
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.LayerSwitcher(),
new OpenLayers.Control.Attribution()],
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
maxResolution: 156543.0399,
numZoomLevels: 19,
units: 'm',
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326")
});
// Define the map layer
// Here we use a predefined layer that will be kept up to date with URL changes
layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");
map.addLayer(layerMapnik);
var lonLat = new OpenLayers.LonLat(0, 0).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
map.zoomTo(3);
map.setCenter(lonLat, 19);
test();
}
</script>
</head>
<body onload="initialize()" >
<div id="map_canvas" style="width: 828px; height: 698px"></div>
</body>
</html>
I'm sure I'm missing some parameter in creation of map or something but I really can't figure which one.
You forget 's' character in this line:
lineLayer.addFeatures([lineFeature]);
Function 'addFeature' doesn't exist: OpenLayers.Layer.Vector.addFeatures
To see the feature, hold Shift key on your keyboard and try to draw a box
EDIT: Ok, now I know how did you want.
You need to create one OpenLayers.Point object for each point you have in your DB. One solution is to use and Ajax call to your own PHP function to retrieve them. The PHP file includes code to get them. I recommend to return them in JSON format (pherhaps an string). Using JQuery framework:
$.ajax({
url: 'your_php_file.php',
dataType: JSON // for example, you can use 'string' type too
success: function(coordinates){
}
});
Now you have a lot of coordinates from your DB. It's time to draw your polygon. Following link can be useful
OpenLayers - how do I draw a Polygon from existing lonLat points?
I hope it helps you. Happy codding!
EDIT2:
linear_ring is an object belongs to OpenLayers.Geometry.LinearRing class. The constructor needs an array of OpenLayers.Geometry.Points and you was giving it OpenLayers.LonLat array.
You need to modify this adding this line after each point creation (modifying the index according to you own code):
points[0] = new OpenLayers.Geometry.Point(points[0].lon,points[0].lat);
So your test function looks like this:
function test(){
lineLayer = new OpenLayers.Layer.Vector("Line Layer");
style = { strokeColor: '#0000ff',
strokeOpacity: 1,
strokeWidth: 10
};
points = new Array();
points[0] =new OpenLayers.LonLat(-2.460181,27.333984 ).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());;
points[0] = new OpenLayers.Geometry.Point(points[0].lon,points[0].lat);
points[1] = new OpenLayers.LonLat(-3.864255,-22.5 ).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());;
points[1] = new OpenLayers.Geometry.Point(points[1].lon,points[1].lat);
var linear_ring = new OpenLayers.Geometry.LinearRing(points);
polygonFeature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Polygon([linear_ring]), null, style);
lineLayer.addFeatures([polygonFeature]);
map.addLayer(lineLayer);
}
The result is this: Image result
Yes, OpenLayers can programatically draw lines. Its even fast enough to draw new lines multiple times a second so you can show live data or animations. Anyway, you have a lot of stuff going on in your code. Perhaps your style is messed up and drawing invisible lines, or your data points are getting transformed incorrectly and the line is off the map. Anyway, I suggest this simple test.
Create a map, and add a vector layer. hang on to the vector layer in a global var called layerVec. Then, run this code.
var CreateLine = function()
{
var pList = new Array();
for(var i=0; i<200; i++)
{
var p = new OpenLayers.Geometry.Point();
p.x = i;
p.y = i;
pList.push(p);
}
var g = new OpenLayers.Geometry.LineString(pList);
var f = new OpenLayers.Feature.Vector(g,null,null);
layerVec.addFeatures(f);
};
Dont worry about coordinates yet, this should be a line in the middle of the map. It may be tiny, or huge depending on your projection, so zoom in.

Categories