首页 > 解决方案 > 如何获取标记的像素坐标

问题描述

每次单击时,我的代码都会在地图上放置一个标记。目标是获取每个时间标记的纬度/经度坐标和像素坐标。到目前为止,我只在获得纬度/经度坐标方面取得了成功。现在下一步是将这些作为输入并计算像素坐标。

<script>
    function initMap() {41.85, -87.65
    var myLatlng = {lat: 41.85, lng: -87.65};
    var map = new google.maps.Map(
          document.getElementById('map'), {zoom: 18,
                                           center: myLatlng,
                                           disableDefaultUI: false,
                                           mapTypeId: 'satellite',
                                           zoomControl: true,
                                           mapTypeControl: true,
                                           scaleControl: true,
                                           streetViewControl: false,
                                           rotateControl: false,
                                           fullscreenControl: true});

    map.setOptions({draggableCursor:'default'});
    map.addListener('click', function(marker){

    marker = new google.maps.Marker({map: map,
                                     clickable: false,
                                     position: marker.latLng,
                                     })

    var markerposLat = marker.getPosition().lat();
    var markerposLon = marker.getPosition().lng();
    
     function pixl(markerposLat,markerposLon){
       var projection = map.getProjection();
       var bounds = map.getBounds();
       var topRight = projection.fromLatLngToPoint(bounds.getNorthEast());
       var bottomLeft = projection.fromLatLngToPoint(bounds.getSouthWest());
       var scale = Math.pow(2, map.getZoom());
       var worldPoint = projection.fromLatLngToPoint(markerposLat,markerposLon);
       return [Math.floor((worldPoint.x - bottomLeft.x) * scale), Math.floor((worldPoint.y - topRight.y) * scale)]
    };

    localStorage["pixl"] = JSON.stringify(pixl);
    localStorage["markerLat"] = JSON.stringify(markerposLat);
    localStorage["markerLon"] = JSON.stringify(markerposLon);
    console.log(localStorage["pixl"],localStorage["markerLat"], localStorage["markerLon"]);
  });

}
</script>

函数 pixl 始终未定义。我意识到这是一个被问过很多次的问题。事实上,我尝试了很多方法。我的出发点是: convert-lat-lon-to-pixels-and-back,当然还有:显示像素和平铺坐标。我无法发现问题。

标签: javascriptgoogle-mapscoordinates

解决方案


请注意,该fromLatLngToPoint方法需要一个google.maps.LatLng类作为其参数。从文档中:

fromLatLngToPoint(latLng[, point])

参数:
latLng:LatLng
点:Point 可选

返回值:Point 可选

从 LatLng 圆柱体平移到 Point 平面。此接口指定一个函数,该函数实现从给定 LatLng 值到地图投影上的世界坐标的转换。Maps API 需要在屏幕上绘制位置时调用此方法。投影对象必须实现此方法,但如果投影无法计算点,则可能返回 null。

所以在你的代码中,我会这样做:

var worldPoint = projection.fromLatLngToPoint(marker.getPosition());

我(和@geocodezip)注意到的另一件事是您没有将参数传递给您的pixl函数。这就是为什么它旨在让您得到undefined回应。为了获得正确的值,您应该包含如下参数:

localStorage["pixl"] = JSON.stringify(pixl((markerposLat,markerposLon)));

这是为此工作的小提琴


推荐阅读