Reputation: 45
I have been trying to check if the direct distance between the user's current location and the shop's location is less than 4km. But when I move the user's marker, the distance measured seems to be less on the side areas of the shop but a lot more in the vertical up and down space of the shop, which doesn't look proportional as I am expecting a circularly consistent behavior. I have been puzzled with this behavior and can't find the solution. Any help or guidance is sincerely appreciated!
<!-- Map Box -->
<script src='https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.js'></script>
<link href='https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.css' rel='stylesheet' />
<script src='https://unpkg.com/@turf/turf/turf.min.js'></script>
<script>
var shop = [18.565461492546987, 73.91061898347883];
var map_msg = document.getElementById('map_msg');
function map_init(lat, long){
L.mapbox.accessToken = 'pk.eyJ1IjoidmR2ZHViZXk3IiwiYSI6ImNrbDVraTNyNDBtZ2EydXBqMnMzamFkZXkifQ.AOlIrevJhdIIK2t5PYIp_A';
var map = L.mapbox.map('map')
.setView([lat, long], 13)
.addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v11'));
var marker2 = L.marker([shop[0], shop[1]], {
draggable: false,
icon: L.mapbox.marker.icon({
'marker-size': 'large',
'marker-symbol': 'shop',
'marker-color': '#2F80ED'
})
}).addTo(map);
var marker = L.marker([lat, long], {
draggable: true,
icon: L.mapbox.marker.icon({
'marker-size': 'large',
'marker-symbol': 'rocket',
'marker-color': '#2F80ED'
})
}).addTo(map);
function onDragEnd() {
console.log('hey');
var lngLat = marker.getLngLat();
console.log('Longitude: ' + lngLat.lng + ' Latitude: ' + lngLat.lat);
}
function distance(x, y){
var to = turf.point([x, y]);
var from = turf.point([shop[0], shop[1]]);
var line = turf.lineString([[x, y], [shop[0], shop[1]]]);
var length = turf.length(line, {units: 'kilometers'});
console.log(length);
var options = { units: 'kilometers' };
var distance_function = turf.distance(to, from, options);
var distance = turf.distance(from, to, options);
console.log("Distance: " + distance + " km");
if(distance > 3){
map_msg.innerHTML = "Sorry, we don't deliver here!";
map_msg.style.color = '#FF4E61';
}else{
map_msg.innerHTML = "Delivery available in this area";
map_msg.style.color = '#3D8B18';
}
}
distance(lat, long);
marker.on('dragend', function(e){
var location = e.target._latlng;
distance(location.lat, location.lng);
});
}
</script>
Upvotes: 1
Views: 402
Reputation: 126225
var shop = [18.565461492546987, 73.91061898347883];
Your project is operating at 74 degrees of latitude. In Web Mercator, at that latitude, there is a significant difference in pixel distance between a degree of latitude and a degree of longitude. (At the equator, there is none).
I haven't inspected your code further, but I imagine it is operating correctly - a squished ellipse is what you would expect. You can verify this by moving your shop to [0, 0]
and seeing if it gives the circle you were expecting.
Upvotes: 1