mercator projection is not working fine? - javascript

I need use mercator projection to point the places by latitude and logitude in my svg application.I have serached a lot and i got these links,
http://en.wikipedia.org/wiki/Mercator_projection
Covert latitude/longitude point to a pixels (x,y) on mercator projection
CODE
//this lat and long is for chicago
var latitude = 41.850033; // (φ)
var longitude = -87.65005229999997; // (λ)
var PI = 3.14;
var mapWidth = 750;
var mapHeight = 380;
// get x value
var x = (mapWidth * (180+longitude) / 360) % mapWidth + (mapWidth / 2);
// convert from degrees to radians
var latRad = latitude * PI / 180;
// get y value
var mercN = Math.log(Math.tan((PI / 4) + (latRad / 2)));
var y = (mapHeight / 2) - (mapWidth * mercN / (2 * PI));
I've used this code in my application, but it doesn't work for me.
Please help to get x and y position from the latitude and longitude.
Any Suggestions should be appreciated.

You forgot the top left and bottom right corner of the map and the factor to multiply the x,y coordinates to give the correct map projection. You can use a fixed map coordinate, i.e. a factor or you can compute the bounding box:Convert lat/lon to pixel coordinate? and then compute the world width and height that fits the map's width and height.

Related

Generate circle points from latitude and longitude from center point and radius

I have (lat, lon) for the center of a circle.
I have a radius R in km.
My code
for (var i = 0; i < steps; i++) {
let degrees = (i/steps)*360
let radians = (Math.PI/180)*degrees
let x = lat + radius * Math.cos(radians)
let y = lon + radius * Math.sin(radians)
coordinates.push([x,y])
}
returns an oval shape because of the latitude and variable radius is not in km, but in coordinates.
How can I adapt this code in order to generate a perfect circle?
For not very large circle radius you can correct longitude dimension using division by cos(latitude), because meridian/parallel ratio depends on this value.

Initiate d3 map over certain area given latitude and longitude

I am building a map in d3 and basing it off of this codepen by Andy Barefoot: https://codepen.io/nb123456/pen/zLdqvM?editors=0010. I want to modify the initiateZoom() function so that if I set the lat/lon coordinates for a box surrounding say Ohio, the map will initialize its panning to be over Ohio.
function initiateZoom() {
minZoom = Math.max($("#map-holder").width() / w, $("#map-holder").height() / h);
maxZoom = 20 * minZoom;
zoom
.scaleExtent([minZoom, maxZoom])
.translateExtent([[0, 0], [w, h]])
;
midX = ($("#map-holder").width() - minZoom * w) / 2;
midY = ($("#map-holder").height() - minZoom * h) / 2;//These are the original values
var swlat = 32;
var swlon = -82;
var nelat = 42;
var nelon = -72;
var projectCoordinates = projection([(swlat+nelat)/2, (swlon+nelon)/2]);
/*This did not work
var midX = minZoom*(w-(swlat+nelat)/2) - ($("#map-holder").width()-(swlat+nelat)/2);
var midY = minZoom*(h-(swlon+nelon)/2) - ($("#map-holder").height()-(swlon+nelon)/2);*/
/*Neither did this
var midX = minZoom*(w-projectCoordinates[0])-($("#map-holder").width()-projectCoordinates[0]);
var midY = minZoom*(h-projectCoordinates[1])-($("#map-holder").height()-projectCoordinates[1]);*/
svg.call(zoom.transform, d3.zoomIdentity.translate(midX, midY).scale(minZoom));
}
The idea behind the original approach was to:
1: Get the current pixel display of the map
2: Get the new pixel distance from the map corner to the map point after zoom has been applied
3: The pixel distance of the center of the container to the top of the container
4: subtract the values from 2 and 3
The original post was trying to translate the map so that it would initialize the zoom and pan over the center of the map. I tried to modify this approach first by directly substituting the lat/lon values into the above equations. I also tried first transforming the lat/lon values using the projection and then substituting those values in, with little success. What do I need to do in order to get my desired result?
Setting a translateExtent could be a bad idea because it depends on the zoom scale.
The following replacement works.
function initiateZoom() {
// Define a "minzoom" whereby the "Countries" is as small possible without leaving white space at top/bottom or sides
minZoom = Math.max($("#map-holder").width() / w, $("#map-holder").height() / h);
// set max zoom to a suitable factor of this value
maxZoom = 20 * minZoom;
// set extent of zoom to chosen values
// set translate extent so that panning can't cause map to move out of viewport
zoom
.scaleExtent([minZoom, maxZoom])
.translateExtent([[0, 0], [w, h]])
;
var swlat = 32;
var swlon = -82;
var nelat = 42;
var nelon = -72;
var nwXY = projection([swlon, nelat]);
var seXY = projection([nelon, swlat]);
var zoomScale = Math.min($("#map-holder").width()/(seXY[0]-nwXY[0]), $("#map-holder").height()/(seXY[1]-nwXY[1]))
var projectCoordinates = projection([(swlon+nelon)/2, (swlat+nelat)/2]);
svg.call(zoom.transform, d3.zoomIdentity.translate($("#map-holder").width()*0.5-zoomScale*projectCoordinates[0], $("#map-holder").height()*0.5-zoomScale*projectCoordinates[1]).scale(zoomScale));
}

Get pixel position from bearing

I need to position a dot on a coordinate system based on its bearing and radius.
Using the following code i can position a dot at the correct distance from the center, but this only works horizontally.
What i need is both top & left position of the dot based on bearing & radius
setTimeout(function() {
var km2show = 100;
var testDistance = 50;
var width = $('#radar').width(); // Width & height of radar
var center = width/2; // Radar center
var px2km = center/km2show; // Pixels per km
var radius = radius2coor((px2km*testDistance),center);
var bearing = 45;
// Set height of radar based on the width
$('#radar').height(width);
// Set dot in center of radar
$('#centerDot').css({top: center, left: center});
$('#container').append("<div style='position:absolute;top:0px;left:"+radius+"px;color:white;'>*</div>");
},100);
function radius2coor(radius,center) {
var res = radius-center;
return res;
}
Please see
jsFiddle
So how would i go about getting bot top and left position of the dot ?
The end result should position the dot at the red marker having a bearing of 45 degrees:
The main issue you were encountering was that the angle wasn't in radians so first thing we want is to convert the 45 degrees to pi/4.
Also, when going from regular angular coordinates to x,y coordinates you multiply the radius by sine of the angle to find y coordinate and you multiply the radius by the cosine of the angle to get the x coordinate. Just think about the unit circle and it will make sense.
var bearing = parseInt(prompt("enter angle in degrees", "0"));
if(!isNaN(bearing)){
setTimeout(function() {
var km2show = 100;
var testDistance = 50;
var width = $('#radar').width(); // Width & height of radar
var center = width/2; // Radar center
var px2km = center/km2show; // Pixels per k
//not sure what this is doing so I set a random radius
//(called it distanceFromCenter). If you need this to be
//the distance between two cartesian points then you can
//just implement the distance formula.
//var radius = radius2coor((px2km*testDistance),center);
var radius = 100;
var radianBearing = (bearing/180)*Math.PI
// Set height of radar based on the width
$('#radar').height(width);
// Set dot in center of radar
$('#centerDot').css({top: center, left: center});
//the main issue you were encountering was that the angle wasn't in radians so I converted it.
positionDot(radius, radianBearing);
},100);
}
function positionDot(distanceFromCenter, bearing, width)
{
//when going from regular angular coordinates to x,y coordinates you multiply the radius by sine of the angle to find y coordinate and you multiply the radius by the cosine of the angle to get the x coordinate.
$('#container').append("<div style='position:absolute;top:"+(-distanceFromCenter*Math.sin(bearing)).toString()+"px;left:"+distanceFromCenter*Math.cos(bearing)+"px;color:white;'>*</div>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id='radar' style='width:100%;max-width:400px;height:400px;border:1px black solid;border-radius:400px;background-color:#3c3c3c;position:relative;'>
<div id='centerDot' style='position:absolute;color:white;'>
<div style='position:relative;' id='container'></div>
<b>*</b>
</div>
</div>
To get both coordinates, you need coordinates of center, radius and bearing.
Note that trigonometric functions usually work with argument in radians, not degrees (don't know about javascript math library)
P.X = Center.X + Radius * Math.Cos(bearing)
P.Y = Center.Y + Radius * Math.Sin(bearing)
You can get it with:
x = center + radius * cos(bearing)
y = center + radius * sin(bearing)
and as MBo said, you have to convert bearing into radians
rad = deg * PI / 180
https://upload.wikimedia.org/wikipedia/sr/8/85/Trig-funkcije1.gif

Parametric equation to place a leaflet marker on the circumference of a circle is not precise?

I am working on an application where I have the center of a circle and the radius and I am plotting the circle with the help of Leaflet.
I placed a marker on the north most end of the circumference and made it draggable.
var circle = L.circle(coords, radius).addTo(map);
convertRadiusToLatitude = parseInt(response.radius)/111111;
var coordsOnRadius = [parseFloat(response.lat) + convertRadiusToLatitude, parseFloat(response.long)];
var markerOnRadius = L.marker(coordsOnRadius, {draggable: true}).addTo(map);
Now, this adds the marker to the circumference and now I wanted it to be draggable only on the circumference itself for which I used the parametric equation.
Parametric equation
x = Xc + R * cos(theta)
y = Yc + R * sin(theta)
Code for dragging
markerOnRadius.on('drag', function(e){
bearing = marker.getLatLng().bearingTo(markerOnRadius.getLatLng());
var markerOnRadiusX = parseFloat(response.lat) + ((0.000009 * parseFloat(response.radius)) * Math.cos( toRad(bearing) ));
var markerOnRadiusY = parseFloat(response.long) + ((0.000009 * parseFloat(response.radius)) * Math.sin( toRad(bearing) ));
markerOnRadius.setLatLng([markerOnRadiusX, markerOnRadiusY]);
});
The bearingTo method:
L.LatLng.prototype.bearingTo = function(other) {
var d2r = L.LatLng.DEG_TO_RAD;
var r2d = L.LatLng.RAD_TO_DEG;
var lat1 = this.lat * d2r;
var lat2 = other.lat * d2r;
var dLon = (other.lng-this.lng) * d2r;
var y = Math.sin(dLon) * Math.cos(lat2);
var x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
var brng = Math.atan2(y, x);
brng = parseInt( brng * r2d );
brng = (brng + 360) % 360;
return brng;
};
Issue
When I start dragging the marker, this code is working fine and brings it back to the circumference at the bearing at which the marker is dragged to. But there is one problem, the coords on the circumference are slightly off and in terms of longitude. When the bearing is 0 (north), the coords are perfect, but when it is 90 (east), the longitude is slightly less that it should for the marker to be at the circumference.
Again at 180 (south), coords are perfect, but at 270 (west), the longitude calculated is slightly less and the marker tends towards the radius again.
So basically if you visualize the marker being dragged, it starts perfectly on the north end and starts coming inside the circle slightly increasing with the bearing till it reacher 90 and then starts going towards the circumference again till 180 when it is perfect again.
It forms more like a ellipse if you get the gist of it.
Could anyone tell me why is longitude coming a little off and why the marker moves in an elliptical path. Has it something to do with the world coordinates and window coordinates. Or are my equations slightly off somewhere?
It does look like a projection issue. In your dragging code you are basically doing
lat = a + r cos(baring)
long = b + r sin(baring)
giving a circle in the Lat-Long coordinates. This would work fine if you were at the equator with Mercator projection. You will get more distortion as you move further towards the polls.
Assume you are using the defaults for Leaflet reference doc You have the EPSG3857 Web Mercator coordinates.
If you want to ensure you have a exact circle it will be better to work using screen coordinates. You can get these using methods on the ICRS objects. First get the coordinate system L.CRS.EPSG3857 and use the latLngToPoint and pointToLatLng methods.
var crs = L.CRS.EPSG3857;
var zoom = ...; // how you calculate your zoom factor
markerOnRadius.on('drag', function(e){
var markerLL = marker.getLatLng()
var morLL = markerOnRadius.getLatLng();
var markerP = crs.latLngToPoint(markerLL,zoom);
var morP = crs.latLngToPoint(morLL,zoom);
// get the distance between the two points
var dist = markerP.distanceTo(morP);
// Get the vector from center to point
var A = morP.subtract(markerP);
// scale so its of the desired length
var B = A. multiplyBy( factor / dist);
// Add on the center
var C = markerP.add(B);
// Convert back to LatLong
var D = crs.pointToLatLng(C,zoom);
markerOnRadius.setLatLong(D);
});

How to get Latitude and Longitude Bounds from Google Maps x y and zoom parameters

I have seen some questions with similar titles, but they seem to be referring to x and y pixel coordinates.
I am asking about the actual tile numbers of x and y from Google Maps getTile() function:
To clarify the question...
Given the x, y, and zoom parameters in the getTile() function, how can I find the latitude and longitude bounds of the tile?
CoordMapType.prototype.getTile = function(coord, zoom, ownerDocument) {
var x = coord.x,
y = coord.y,
url = "http://mt1.google.com/vt/lyrs=y&x="+x+"&y="+y+"&z="+zoom;
//other stuff
}
The only reason at the moment that I need this is that I want to determine the maximum zoom level at this tile projection. From this link: Maximum Zoom, it states that in order to find the maximum zoom, I will need a latitude and longitude value using getMaxZoomAtLatLng(). So if I can get the bounds, then I can use any latitude and longitude points within the bounds to find my max Zoom.
Alternatives I have thought of were creating an image and checking if the src url had an error (this seems like a terrible idea to me, as I would be making many bad requests just to check if imagery existed).
var img = new Image;
img.onload = function() {/*imagery exists*/ }
img.onerror = function() {/*past maximum zoom*/ }
img.src = url;
EDIT:
After further investigation, I realize that the getMaxZoomAtLatLng() function is using an ajax call which will not fit into my plans. But I still am interested in how to find the latitude and longitude boundaries of a given tile ( that could be useful for other applications ).
Assuming a basic google-map using mercator-projection and a tileSize of 256x256:
The number of tiles on each(x-axis and y-axis) is Math.pow(2,zoom), so on zoom 0 the map is using 1 tile, on zoom 1 4 tiles, on zoom 2 16 tiles and so on.
First calculate the southWest/northeast-points of the tile.
the size of a tile (in points) is 256/Math.pow(2,zoom)
southWest-point:
x = tile.x * tileSizeInPoints
y = (tile.y * tileSizeInPoints) + tileSizeInPoints
northEast-point:
x = (tile.x * tileSizeInPoints) + tileSizeInPoints
y = tile.y * tileSizeInPoints
These points must be translated to LatLngs. When you use a map you may use the method fromLatLngToPoint of the maps projection.
For a custom implementation take a look at https://developers.google.com/maps/documentation/javascript/examples/map-coordinates.
A possible API-independant implementation:
MERCATOR={
fromLatLngToPoint:function(latLng){
var siny = Math.min(Math.max(Math.sin(latLng.lat* (Math.PI / 180)),
-.9999),
.9999);
return {
x: 128 + latLng.lng * (256/360),
y: 128 + 0.5 * Math.log((1 + siny) / (1 - siny)) * -(256 / (2 * Math.PI))
};
},
fromPointToLatLng: function(point){
return {
lat: (2 * Math.atan(Math.exp((point.y - 128) / -(256 / (2 * Math.PI)))) -
Math.PI / 2)/ (Math.PI / 180),
lng: (point.x - 128) / (256 / 360)
};
},
getTileAtLatLng:function(latLng,zoom){
var t=Math.pow(2,zoom),
s=256/t,
p=this.fromLatLngToPoint(latLng);
return {x:Math.floor(p.x/s),y:Math.floor(p.y/s),z:zoom};
},
getTileBounds:function(tile){
tile=this.normalizeTile(tile);
var t=Math.pow(2,tile.z),
s=256/t,
sw={x:tile.x*s,
y:(tile.y*s)+s},
ne={x:tile.x*s+s,
y:(tile.y*s)};
return{sw:this.fromPointToLatLng(sw),
ne:this.fromPointToLatLng(ne)
}
},
normalizeTile:function(tile){
var t=Math.pow(2,tile.z);
tile.x=((tile.x%t)+t)%t;
tile.y=((tile.y%t)+t)%t;
return tile;
}
}
call MERCATOR.getTileBounds() by supplying a single object as argument with the following format:
{
x:tileIndexX,
y:tileIndexY,
z:zoom
}
Demo: http://jsfiddle.net/doktormolle/55Nke/
I think Google maps tiling system is similar to the Bings maps tiling system. The tiles start from the upper left in the lower right and each tile is 256x256:http://msdn.microsoft.com/en-us/library/bb259689.aspx.
Not sure if this entirely helps with the bounds, but to find an easy display of the tile coordinates I went here:
https://developers.google.com/maps/documentation/javascript/examples/map-coordinates
And to typescript on the line:
const chicago = new google.maps.LatLng(-33.76781028848151, 150.73644505329204
);
Change the lat/long to wherever you want... And they have a nice UI that calculates all the changes on zoom.

Categories

Resources