我正在尝试使用geolocation
来获取我当前的位置,这会将lat
和lon
插入到地图的中心点。 我知道geolocation
是异步的,所以我必须获取该值,然后调用另一个函数才能向前传递。 由于某种原因,我没有创建对象mymap。
<script>
function foundLocation(pos) {
setMyLocation(pos.coords.latitude, pos.coords.longitude)
};
function noLocation() {
document.getElementById("warning").innerHTML = "Could not find your location";
};
function setMyLocation(myLat, myLon) {
L.marker([ myLat, myLon ], {icon: homeIcon}).bindPopup("You Are Here").addTo(coolPlaces);
var mymap = L.map('mapid', {
center: [ myLat, myLon ],
minZoom: 2,
maxZoom: 18,
zoom: 15,
layers: [mymarkers]
});
};
navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
<snip other JS irrelevant stuff>
</script>
有没有办法让我把这两个variables
从function
中取出并创建mymap对象? 我不精通JS
及其限制。
上面的代码导致未生成地图。 我必须将mymap带到geolocation
函数之外才能发生这种情况。 问题是我不知道如何将myLat和myLon发送到该声明之外。
@espascarello点赞:成功函数中的所有映射功能都foundLocation(pos)
.
更新:问题出在上面。 阅读它。 将每个地图功能都放在里面foundLocation(pos)
工作正常。 如果找不到这两个变量,则任何映射函数都没有用。
myLat = 0
myLon = 0
mymap = ""
function foundLocation(pos) {
myLat = pos.coords.latitude;
myLon = pos.coords.longitude;
// setMyLocation(pos.coords.latitude, pos.coords.longitude)
var homeIcon = L.icon({
iconUrl: '/img/house_marker.png',
iconSize: [24, 24],
iconAnchor: [12, 24],
popupAnchor: [0, -24]
});
var mymarkers = L.layerGroup([
L.marker([ myLat, myLon ], {icon: homeIcon}).bindPopup("You Are Here"),
<%= @markers %>
]);
var mymap = L.map('mapid', {
center: [ myLat,myLon ],
minZoom: 2,
maxZoom: 18,
zoom: 15,
layers: [mymarkers]
});
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
attribution: 'Map data © <a href="http://openstreetmap.org" target="_blank">OpenStreetMap</a> Imagery © <a href="http://mapbox.com" target="_blank">Mapbox</a>',
id: 'mapbox.streets'
}).addTo(mymap);
L.control.layers(mymarkers).addTo(mymap);
};
function noLocation() {
document.getElementById("warning").innerHTML = "Could not find your location";
};
function setMyLocation(pushLat, pushLon) {
alert("inside setMyLocation");
myLat = pushLat;
myLon = pushLon;
// var mymap = L.map('mapid', {
// center: [ myLat, myLon ],
// minZoom: 2,
// maxZoom: 18,
// zoom: 15,
// layers: [mymarkers]
// });
};
navigator.geolocation.getCurrentPosition(foundLocation, noLocation);