gpt4 book ai didi

javascript - 接近地球极限时范围内随机坐标的问题

转载 作者:行者123 更新时间:2023-12-03 00:09:54 24 4
gpt4 key购买 nike

我正在 map 范围内创建一个随机点,其中中心是我给出的地理坐标。

var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();

var ptLat = Math.random() * (ne.lat() - sw.lat()) + sw.lat();
var ptLng = Math.random() * (ne.lng() - sw.lng()) + sw.lng();
var point = new google.maps.LatLng(ptLat,ptLng);

在大多数情况下一切都很好,但在例如 -7.47、178.67 的情况下,就会出现问题,因为经度的界限将为 142、-142,并且会弄乱随机数,因为它可以返回值如20,30或40,它们在数字范围内,但不在坐标范围内。

计算一定范围内的纬度或经度随机数而不弄乱的最佳选择是什么?

最佳答案

使用LatLngBounds.toSpan

var bounds = map.getBounds();
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
var span = bounds.toSpan();
var ptLat = Math.random() * span.lat() + sw.lat();
var ptLng = Math.random() * span.lng() + sw.lng();
var point = new google.maps.LatLng(ptLat, ptLng);

proof of concept fiddle

screenshot of resulting map with multiple random markers

代码片段:

var map;

function initMap() {
var myLatLng = {
lat: 64.197671,
lng: -152.009373
};

map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: myLatLng
});

var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
createRandomMarker();
});
}

function createRandomMarker() {
var bounds = map.getBounds();
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
var span = bounds.toSpan();
console.log("span=" + span.toUrlValue(6) + "; sw=" + sw.toUrlValue(6) + " ne=" + ne.toUrlValue(6));
var ptLat = Math.random() * span.lat() + sw.lat();
var ptLng = Math.random() * span.lng() + sw.lng();
var point = new google.maps.LatLng(ptLat, ptLng);
var marker2 = new google.maps.Marker({
position: point,
map: map,
title: 'Random point'
});
console.log("random marker at:" + marker2.getPosition().toUrlValue(6));
if (!bounds.contains(marker2.getPosition())) {
alert("marker out of bounds:" + marker2.getPosition().toUrlValue());
}
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}

#map {
height: 90%;
margin: 0;
padding: 0;
}
<input type="button" onclick="createRandomMarker();" value="makeMarker" />
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>

关于javascript - 接近地球极限时范围内随机坐标的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54788681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com