I have a latitude and longitude of some point. How to conver its to the OpenLayer 3 map coordinate system?
My code is:
...requiries...
var coord = [55.7522200, 37.61556005];
//coord = ol.proj.transform(coord,'EPSG:4326', 'EPSG:3857');
var vectorSource = new ol.source.GeoJSON(
({
object: {
'type': 'FeatureCollection',
'crs': {
'type': 'name',
'properties': {
'name': 'EPSG:3857'
}
},
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': coord
}
}
]
}
}));
...
var map = ...
Could you gave me an example for converting the var coords on JavaScript.
You can see this example of code at link http://openlayers.org/en/v3.0.0/examples/geojson.html
If you have a coordinate [lon, lat] (in that order) you can transform it using:
var newCoord = ol.proj.transform([lon, lat], 'EPSG:4326', 'EPSG:3857');
try this
var Coord = ol.proj.transform([lon, lat], 'EPSG:4326', 'EPSG:3857');
Related
I'm trying to add polynomial regression line to my google trends live graph but it does not work properly:
as you can see the polynomial regression trendline is not fitting the data points properly (it's straight trendline and not a polynomial trendline).
My code is:
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time of Day');
data.addColumn('number', 'Depth');
var options = {
title: 'graph',
legend: 'none',
crosshair: { trigger: 'both', orientation: 'both' },
trendlines: {
0: {
type: 'polynomial',
degree: 3,
visibleInLegend: true,
}
},
hAxis: {
viewWindow: {
min: new Date(),
}
},
vAxis: {
viewWindow: {
min: 0,
max: 100
}
}
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart'));
chart.draw(data, options);
var interval = setInterval(function() {
var time = new Date();
data.addRow([time, newValue])
chart.draw(data, options);
}, 10);
I have an issue that is driving me crazy. I have an openlayers map project that works fine. I took this concept code and moved it to a project that utilizes .Net and the projection for the markers/icons get messed up.
//set the Icon/Marker that will be used
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.8,
src: '<%=PinMarkerImage%>'
}))
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: iconStyle
});
//we will zoom the map to fit the locations after we create
//the map
var mapObj = new ol.Map({
layers: [new ol.layer.Tile({ source: new ol.source.OSM() }), vectorLayer],
target: document.getElementById('map-canvas'),
view: new ol.View({
center: ol.proj.fromLonLat([0, 0]),
zoom: 12
})
});
alert(vectorSource.getExtent());
mapObj.getView().fit(vectorSource.getExtent(), { padding: [75, 40, 40, 75], constrainResolution: false });
//I pass in an object one at a time to populate the features
function changeMapOption(oBranch, i) {
// alert('selected');
var long = oBranch.Longitude;
var lat = oBranch.Latitude;
alert(long + ' ' + lat);
//lastCord = ol.proj.transform([coord[0], coord[1]], 'EPSG:4326', 'EPSG:3857');
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857')), //ol.proj.fromLonLat([long, lat])),
id: oBranch.Id,
title: oBranch.Name,
address: oBranch.Address + ", " + oBranch.City + ", " + oBranch.State + " " + oBranch.ZipCode
});
//alert(iconFeature.getGeometry());
vectorSource.addFeature(iconFeature);
//mapObj.getView().fit(vectorSource.getExtent(), { padding: [75, 40, 40, 75], constrainResolution: false });
//target = mapObj.getTarget();
//This will zoom the map to fit all of the vector Sources in vectorSource
//alert(vectorSource.getExtent());
//mapObj.addOverlay(popup);
//jTarget = typeof target === "string" ? $("#" + target) : $(target);
//element = document.getElementById('popup');
}
I have the alerts set to check the Longitude and Latitude. These are correct. For this test run I have three objects that are populated, the Longitude and Latitudes are as follows:
-112.04883, 40.492104
-95.673328, 29.95752
-95.638558, 29.880014
When I run the code the alert for the vectorSource.getExtent() produces this:
-12473218.699582075,-8426499.834030088,-10646435.576762961,-6361484.120029401
And the markers show up off the lower coast of Chile. The Latitude is wrong, yet the Longitude appears to be correct.
I could certainly use some guidance here. This is driving me crazy.
Thanks for any assistance.
After trying multiple times, I came up with a solution that works. Hopefully this will help someone down the line.
function loadMarker(oBranch, i) {
var sHTML = getMarkerInfoHtml(oBranch);
var long = oBranch.Longitude * 1;
var lat = oBranch.Latitude * 1;
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat(([long, lat]))),
index: oBranch.Id,
id: oBranch.Id,
title: oBranch.Name,
address: sHTML //oBranch.Address + ", " + oBranch.City + ", " + oBranch.State + " " + oBranch.ZipCode
});
vectorSource.addFeature(iconFeature);
}
The key was these two lines:
var long = oBranch.Longitude * 1;
var lat = oBranch.Latitude * 1;
by adding the * 1 to the line it forces JavaScript to treat the variables properly as numeric. It now places the markers in the correct location.
I am trying to do a point cluster layer based on the JSON objects I obtained from database. Here is my JavaScript to plot a point cluster layer:
function addClusters() {
$.ajax({
url: "index.aspx/getBusCommuter",
type: "POST",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = JSON.parse(data.d);
$.each(parsed, function (i, jsondata) {
var coordXicon = jsondata.BusStopX;
var coordYicon = jsondata.BusStopY;
var commuterAmt = jsondata.CommuterAmt;
var latlng = new esri.geometry.Point({ "x": coordXicon, "y": coordYicon, "spatialReference": { "wkid": 4326 } });
// cluster layer that uses OpenLayers style clustering
clusterLayer = new ClusterLayer({
"data": commuterAmt,
"distance": 100,
"id": "clusters",
"labelColor": "#fff",
"labelOffset": 10,
"resolution": map.extent.getWidth() / map.width,
"singleColor": "#888"
});
var defaultSym = new SimpleMarkerSymbol().setSize(4);
var renderer = new ClassBreaksRenderer(defaultSym, "clusterCount");
var picBaseUrl = "http://static.arcgis.com/images/Symbols/Shapes/";
var blue = new PictureMarkerSymbol(picBaseUrl + "BluePin1LargeB.png", 32, 32).setOffset(0, 15);
var green = new PictureMarkerSymbol(picBaseUrl + "GreenPin1LargeB.png", 64, 64).setOffset(0, 15);
var red = new PictureMarkerSymbol(picBaseUrl + "RedPin1LargeB.png", 72, 72).setOffset(0, 15);
renderer.addBreak(0, 2, blue);
renderer.addBreak(2, 200, green);
renderer.addBreak(200, 1001, red);
clusterLayer.setRenderer(renderer);
map.addLayer(clusterLayer);
});
},
error: function (request, state, errors) {
}
});
}
However, when I try to run it, it told me an error message which is clusterLayer is not defined. I wonder which part I missed and am I doing in the correct way.
Also, I wonder is it possible/correct to set the commuterAmt I obtained to data so that for each point on the map will be attached with the correct amount?
I get the reference from: ArcGIS Documentation
Thanks in advance.
Try to download the sample code ArcGIS Documentation
Include ClusterLayer.js from extras direxctory
var dojoConfig = {
paths: {
extras: location.pathname.replace(/\/[^/]+$/, "") + "/extras"
}
};
then in your code use
define dojo.provide("extras.ClusterLayer");
and call
clusterLayer = new extras.ClusterLayer({
"data": commuterAmt,
"distance": 100,
"id": "clusters",
"labelColor": "#fff",
"labelOffset": 10,
"resolution": map.extent.getWidth() / map.width,
"singleColor": "#888"
});
I have two arrays containing latitude and longtitude of 7 locations,and I use the following
code for getting the location of these 7 points:
var geocoder;
initialize();
codeLatLng();
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng() {
var arrlat=[45.95268273, 47.00196833,45.99168238, 46.2186456, 45.91612197, 45.91606814, 45.91606814];
var arrlon=[-66.68426012, -65.56480221, -63.98068545, -64.44419501, -66.74801471, -66.74810832, -66.74810832];
var input = document.getElementById("latlng").getAttribute('value');
console.log(input);
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
for(var i=0;i<arrlat.length;i++)
{
var latlng = new google.maps.LatLng(arrlat[i], arrlon[i]);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
//document.getElementById("test").innerHTML = '' + (results[4].formatted_address); + ''
alert(results[4].formatted_address);
});
}
}
whenever I feed the arrays with 5 of less elements the code works properly but for more than 5 I get 5 alert showing the location of the first 5 elements but for the last 2 I get the following error:
Uncaught TypeError: Cannot read property '4' of null
And here is the Jfiddle link:
link
Can anyone help?
Code more defensively. Check the status of the response before using it. If it isn't "OK", there won't be any results to process.
function codeLatLng() {
var arrlat=[45.95268273, 47.00196833,45.99168238, 46.2186456, 45.91612197, 45.91606814, 45.91606814];
var arrlon=[-66.68426012, -65.56480221, -63.98068545, -64.44419501, -66.74801471, -66.74810832, -66.74810832];
var input = document.getElementById("latlng").getAttribute('value');
console.log(input);
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
for(var i=0;i<arrlat.length;i++)
{
var latlng = new google.maps.LatLng(arrlat[i], arrlon[i]);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK ) {
//document.getElementById("test").innerHTML = '' + (results[4].formatted_address); + ''
if (results.length >= 5)
alert(results[4].formatted_address);
else alert("less than 5 results");
} else alert("reverse geocode failed, status="+status);
});
}
}
See the documentation on Status Codes for what the failure codes mean.
I have Yandex map tiles (Russian) working in Google Maps API v2 but something's not working in Google Maps API v3, see the following jsfiddle: http://jsfiddle.net/VkGjq/1/
Note that when switching between the Google road map and the Yandex tiles they don't line up & the marker is in the wrong position.
For Maps v2, I made an equivalent jsfiddle but it's broken since it needs an API key: http://jsfiddle.net/ggrgQ/1/
You can see similar code here, but you will have to navigate to Moscow manually as Yandex doesn't have any decent data outside of Russia: http://gpsloglabs.com/share/2367c16f3a0e75b05ac8a5529afba225dd929518/
I don't recall where I got the v3 code, but the constants appear to roughly correspond to the v2 version. Other than that, I don't understand what the projection is doing so I'm stuck.
Any ideas?
The code from the jsfiddle is as follows:
var center = new google.maps.LatLng(55.75, 37.62);
var mapOptions = {
zoom: 10,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
new google.maps.Marker({map: map, position: center});
map.mapTypes.set("Yandex",
new google.maps.ImageMapType(
{getTileUrl: function(coord, zoom) {
return "http://vec0"+((coord.x+coord.y)%5)+".maps.yandex.net/tiles?l=map&v=2.16.0&x=" +
coord.x + "&y=" + coord.y + "&z=" + zoom + "";
},
tileSize: new google.maps.Size(256, 256),
isPng: true,
alt: "Yandex",
name: "Yandex",
projection: new YandexProjection(),
maxZoom: 17}));
map.setOptions({mapTypeControlOptions: {mapTypeIds: [google.maps.MapTypeId.ROADMAP, "Yandex"]} });
function YandexProjection() {
this.pixelOrigin_ = new google.maps.Point(128,128);
var MERCATOR_RANGE = 256;
this.pixelsPerLonDegree_ = MERCATOR_RANGE / 360;
this.pixelsPerLonRadian_ = MERCATOR_RANGE / (2 * Math.PI);
this.fromLatLngToPoint = function(latLng) {
function atanh(x) {
return 0.5*Math.log((1+x)/(1-x));
}
function degreesToRadians(deg) {
return deg * (Math.PI / 180);
}
function bound(value, opt_min, opt_max) {
if (opt_min != null) value = Math.max(value, opt_min);
if (opt_max != null) value = Math.min(value, opt_max);
return value;
}
var origin = this.pixelOrigin_;
var exct = 0.0818197;
var z = Math.sin(latLng.lat()/180*Math.PI);
return new google.maps.Point(origin.x + latLng.lng() *this.pixelsPerLonDegree_,
Math.abs(origin.y - this.pixelsPerLonRadian_*(atanh(z)-exct*atanh(exct*z))));
};
this.fromPointToLatLng = function(point) {
var origin = this.pixelOrigin_;
var lng = (point.x - origin.x) / this.pixelsPerLonDegree_;
var latRadians = (point.y - origin.y) / -this.pixelsPerLonRadian_;
var lat = Math.abs((2*Math.atan(Math.exp(latRadians))-Math.PI/2)*180/Math.PI);
var Zu = lat/(180/Math.PI);
var Zum1 = Zu+1;
var exct = 0.0818197;
var yy = -Math.abs(((point.y)-128));
while (Math.abs(Zum1-Zu)>0.0000001){
Zum1 = Zu;
Zu = Math.asin(1-((1+Math.sin(Zum1))*Math.pow(1-exct*Math.sin(Zum1),exct))
/ (Math.exp((2*yy)/-(256/(2*Math.PI)))*Math.pow(1+exct*Math.sin(Zum1),exct)));
}
if (point.y>256/2) {
lat=-Zu*180/Math.PI;
} else {
lat=Zu*180/Math.PI;
}
return new google.maps.LatLng(lat, lng);
};
return this;
}
It turns out that the projection property can't be set via the ImageMapTypeOptions and has to be assigned after the ImageMapType has been constructed, this jsfiddle now works: http://jsfiddle.net/VkGjq/2/
var yandexMapType = new google.maps.ImageMapType(
{getTileUrl: function(coord, zoom) {
return "http://vec0"+((coord.x+coord.y)%5)+".maps.yandex.net/tiles?l=map&v=2.16.0&x=" +
coord.x + "&y=" + coord.y + "&z=" + zoom + "";
},
tileSize: new google.maps.Size(256, 256),
isPng: true,
alt: "Yandex",
name: "Yandex",
maxZoom: 17});
// projection is ignored if passed to MapTypeOptions
yandexMapType.projection = new YandexProjection();
map.mapTypes.set("Yandex", yandexMapType);
By license agreement you can't use yandex maps without yandex api. You can't use yandex tiles in leaflet.
You need to wrap yandex api or use http://leafletjs.com/plugins.html
Or write own a wrapper.
Example https://all-maps.herokuapp.com/
https://github.com/artamonovdev/all-maps