0

I'm filtering the number of cities in a JSON file that are within 10 miles (16 km) of Los Angeles (LA).

I can retrieve the latitude and longitude of LA no problem, but I need to use "latLng.lat" and "latLng.lng" in my "filtered" variable.

The error shows:

Uncaught TypeError: Cannot read property 'latLng' of undefined

Code

var location = 'Los Angeles';

const geocoder = new google.maps.Geocoder()

let city = location + ',us';

var latLng = {};
geocoder.geocode({
    address: city
}, function(results, status) {
    if (status === 'OK') {
        const result = results[0].geometry.location
        const lat = result.lat()
        const lng = result.lng()
        var latLng = {
            lat,
            lng
        }
        console.log(latLng.lat+', '+latLng.lng );

    }
});

if (location != '') {

    var filtered = data.filter(function(item) {

        //can't use latLng here
        return  getDistance(latLng.lat, latLng.lng, data.lat, data.lng) <= 10;
    });

}

console.log(filtered.length);

I need to be able to use latLng.lat and latLng.lng in "filtered".

Community
  • 1
  • 1
TrimTrimm
  • 103
  • 1
  • 9
  • Maybe you don't need to redeclare your latLng with var? And something else, geocoder is async function. – Radonirina Maminiaina Jun 26 '19 at 10:24
  • Where does `data` come from? Also add a `console.dir(item);` to the function doing the data.filter-ing. – Adder Jun 26 '19 at 10:26
  • Your error message is indicating something else than what you have in yours code. It says "_Cannot read property 'latLng' of undefined_" which means that you have tried `someVar.latLng`, yet I cannot find such call in your code. – KarelG Jun 26 '19 at 10:26

0 Answers0