laravelfaker

How with laravel 10 factory make valid place lat, lng?


On laravel 10 site with factory I make a lot of points to show them on Leaflet map :

        $city = $faker->city;
        $lat = $faker->latitude;
        $lng = $faker->longitude;

But looks city name and point are different I need city name with valid lat/lon. If possible wit some country defined, as for any person I have a country (2 char code). ?

"laravel/framework": "^10.48.12",
“8.0.36-0ubuntu0.22.04.1”

Thanks in advance!


Solution

  • There are many lists out there with cities and there according latitude and longitude values:

    I have found this one. It is quite old but should have enough entries to get you going: https://github.com/bahar/WorldCityLocations?tab=readme-ov-file

    Or this one: https://simplemaps.com/data/world-cities. It has a free version, which requires attribution, where you can download a CSV or XLSX file and retrieve the data from there. Here is an example of how I read the data and saved only the necessary data into a JSON file. You can then use a random city from that JSON file.

    $file = fopen(storage_path('worldcities.csv'), 'r');
    
    $cities = [];
    $row = 1;
    while (($data = fgetcsv($file)) !== false) {
       if($row === 1) {
          $row++;
          continue;
       }
    
       $cities[] = [
           'city' => $data[0],
           'lat' => $data[2],
           'lng' => $data[3],
       ];
    
       $row++;
    }
    fclose($file);
    
    Storage::put('cities.json', json_encode($cities));
    

    But you have to be careful because of the huge amount of entries. Another way to do so, would be to read the CSV file every time and choose a random row bigger than one, which might be more memory efficient. Of course, you can save the entries in the DB as well. It all depends on your preferences.