在条件调用函数时使用常量

问题描述 投票:0回答:1

我正在尝试获取最终用户的位置,如果他们位于服务区域(聚)内,请让他们知道。除了输出条件之外,我已经设法使所有功能正常运行。

我正在通过以下方式获取地理位置:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
  });
} else {
  console.log("Geolocation is not supported by this browser.");
}

我的多聚检测是:

polygone=   [
    [43.163834,-84.134153],
    [43.163834,-83.420042],
]

function isPointInPoly(point, vs) {
    var x = point[0], y = point[1];
    var inside = false;
    for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
        var xi = vs[i][0], yi = vs[i][1];
        var xj = vs[j][0], yj = vs[j][1];
        var intersect = ((yi > y) != (yj > y))
            && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
        if (intersect) inside = !inside;
    }

    return inside;
};

我尝试过的:

if(isPointInPoly([ $latitude, $longitude ], polygone) === true) {
    $("#output").html('Yup');
} else {
    $("#output").html('Nope');
}

我不确定我是否正确地处理了这个问题,但我查找了“在条件中使用 const”和其他一些术语,但无济于事。

我也在这里设置了一个小提琴

最后我只想向该区域内的用户显示一条消息,向该区域外的用户显示另一条消息。

javascript function conditional-statements geolocation constants
1个回答
0
投票

您应该将条件放在获取坐标的函数内。

由于

const
let
是块作用域,因此您不能在函数外部使用。

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);

    if(isPointInPoly([ latitude, longitude ], polygone) === true) {
      $("#output").html('Yup');
    } else {
      $("#output").html('Nope');
    }

  });
} else {
  console.log("Geolocation is not supported by this browser.");
}
© www.soinside.com 2019 - 2024. All rights reserved.