I am currently trying to calculate the distance between two values using the computeDistanceBetween() function:
- Store location
- Place location (via place.geometry.location)
Here is my source code for reference:
Below is the respective store locations which I have enclosed in an array of objects
const storeGeometry = [
{
storeid: "01",
storeLat: -35.1206903,
storeLng: 173.2579736,
},
{
storeid: "02",
storeLat: -35.723671,
storeLng: 174.321526,
},
{
storeid: "03",
storeLat: -36.898763,
storeLng: 174.806818,
},
{
storeid: "04",
storeLat: -37.782266,
storeLng: 175.289039,
},
{
storeid: "05",
storeLat: -37.645333,
storeLng: 176.187332,
},
{
storeid: "06",
storeLat: -38.134894,
storeLng: 176.24952,
},
{
storeid: "07",
storeLat: -38.664048,
storeLng: 178.02508,
},
{
storeid: "08",
storeLat: -39.057999,
storeLng: 174.073376,
},
{
storeid: "09",
storeLat: -39.495198,
storeLng: 176.913198,
},
{
storeid: "10",
storeLat: -40.352036,
storeLng: 175.6119,
},
{
storeid: "11",
storeLat: -40.94813,
storeLng: 175.657805,
},
{
storeid: "12",
storeLat: -41.284706,
storeLng: 174.773618,
},
{
storeid: "13",
storeLat: -41.270735,
storeLng: 173.285271,
},
{
storeid: "14",
storeLat: -43.523548,
storeLng: 172.642151,
},
{
storeid: "15",
storeLat: -44.396682,
storeLng: 171.248143,
},
{
storeid: "16",
storeLat: -45.095388,
storeLng: 170.972719,
},
{
storeid: "17",
storeLat: -45.870951,
storeLng: 170.511253,
},
{
storeid: "18",
storeLat: -46.409178,
storeLng: 168.353493,
},
];
Here is the logic to calculate the distance based off both values within storeLat, storeLng, placeLat, placeLng
places.forEach((place) => {
if (!place.geometry || !place.geometry.location) {
//console.log("Returned place contains no geometry");
return;
}
if (place.geometry) {
const storeLat = storeGeometry.map((store) => store.storeLat);
const storeLng = storeGeometry.map((store) => store.storeLng);
// console.log("Store lat: " + storeLat + " Store lng: " + storeLng);
const placeLat = place.geometry.location.lat();
const placeLng = place.geometry.location.lng();
// console.log("Place lat: " + placeLat + " Place lng: " + placeLng);
console.log(typeof storeLat, typeof storeLng);
console.log(typeof placeLat, typeof placeLng);
const distance =
google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(placeLat, placeLng),
new google.maps.LatLng(storeLat, storeLng)
);
console.log("Distance: " + distance)
}
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
The issue lies when I check the respective types of storeLat and storeLng, it returns object object. In contrast, placeLat and placeLng returns number number. So when I console log distance, it returns NaN.
Is there anyway I can convert the type of storeLat and storeLng to a number so I can successfully compute the distance?