将lat/lng坐标转换为给定地图上的像素(使用JavaScript)

Conversion of lat/lng coordinates to pixels on a given map (with JavaScript)

本文关键字:像素 使用 JavaScript 地图 lng lat 坐标 转换      更新时间:2023-09-26

我从MaxMind建立了一个城市数据库,其中包括数据库中每个城市的lat/lng值。我还整理了一张北美地图,我想在地图的x/y坐标上出现一个图标,该图标来自城市数据库记录的lat/lng坐标。

根据我的理解,我需要首先找到地图的左/上边界(lat/lng->x/y),然后将其作为任何北美城市x/y坐标之间线性关系的差值。最后,根据地图的大小,只需进行一些简单的除法和减法运算即可确定点的位置。

然而,我似乎不知道如何做到以下几点:

  1. 我不确定纬度/经度映射系统是什么。我该怎么找到它
  2. 使用JavaScript库,我如何将0,0坐标和每个城市坐标的lat/lng转换为像素。我试过Proj4js,但它们要求你指定坐标图类型等等。将给定图片上的长/宽转换为像素x/y

有什么想法吗?

--编辑--

(北美的)输出图是一个连续的圆柱体:"米勒圆柱投影"。http://en.wikipedia.org/wiki/Miller_cylindrical_projection

纬度和经度是在地球上绘制的假想线,因此您可以准确地定位世界上的任何位置。简单地说,它们是平面的X坐标和Y坐标。纬度是一条从北向南的垂直线,北极为90度,南极为-90度。

另一方面,经度是一条从东到南的水平线,西为-180度,东为180度。

您可以将latLng转换为像素坐标,假设html容器的宽度是世界的宽度,高度也是如此。

公式-经度-像素

(givenLng*widthOfContainerElement)/360

其中360是以度为单位的总经度

公式-纬度-像素化

(givenLat*heightOfContainerElement)/180

其中360是以度为单位的总经度

//Height is calculated from the bottom

如果你还需要澄清,请告诉我。

这是一个墨卡托投影的Javascript实现,它只返回正值(屏幕的笛卡尔坐标系),并说明球面>平面转换:

// get x   
var x = (lng + 180) * (mapWidth / 360);
// convert from degrees to radians
var latRad = lat * Math.PI / 180;
// get y value
var mercN = Math.log(Math.tan((Math.PI / 4) + (latRad / 2)));
var y = (mapHeight / 2) - (mapWidth * mercN / (2 * Math.PI));

这是一个非常古老的问题,但公认的答案有一些。。。细微差别。。。

通常,这是针对卫星/航空图像进行的,通常伴随着"缩放级别"

这个缩放级别大致(我的意思是大致)转换为"地面采样距离"或GSD,当提供时,它表示图像中每像素的厘米数。

您经常会看到缩放级别为18、19、20或21。

需要注意的问题之一是,地球既不是平面的,也不是完美的球形,因此,有许多不同的"投影"方法可以将地球表面的三维坐标转换为屏幕上的二维图像。这些投影方法中最流行和最广泛使用的是墨卡托投影。

Google提供了一种使用墨卡托投影来提供xy的像素坐标的方法。

然后,我们可以使用"缩放级别"缩放坐标以适应我们的图像。

interface LatLngLiteral {
    lat: number;
    lng: number;
}
interface Coordinate {
    x: number;
    y: number;
}
const project = (latLng: LatLngLiteral): Coordinate => {
    const TILE_SIZE: number = 256;
    let siny: number = Math.sin((latLng.lat * Math.PI) / 180);
    // Truncating to 0.9999 effectively limits latitude to 89.189. This is
    // about a third of a tile past the edge of the world tile.
    siny = Math.min(Math.max(siny, -0.9999), 0.9999);
    return {
        x: TILE_SIZE * (0.5 + latLng.lng / 360),
        y: TILE_SIZE * (0.5 - Math.log((1 + siny) / (1 - siny)) / (4 * Math.PI))
    };
};
export function formatToPoint(latLng: LatLngLiteral, zoom: number): Coordinate {
    // Get the world coordinates in pixels
    const worldCoordinate: Coordinate = project(latLng);
    // Scale to fit our image
    const scale: number = Math.pow(2, zoom);
    // Apply scale to world coordinates to get image coordinates
    return {
        x: Math.floor(worldCoordinate.x * scale),
        y: Math.floor(worldCoordinate.y * scale)
    }
}