sarker306

Find Nearest Cities, given Latitude, Longitude

Aug 11th, 2023 (edited)
1,339
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | Source Code | 0 0
  1. /* You must install JSONCpp library to use this program.
  2.    Compile this file using this command:
  3.    c++ -o nearestcity nearestcity.cc -ljsoncpp
  4. */
  5. #include <iostream>
  6. #include <cstdlib>
  7. #include <iomanip>
  8. #include <fstream>
  9. #include <limits>
  10. #include <cmath>
  11. #include <queue>
  12. #include <json/json.h>
  13.  
  14. double find_distance(double lat1, double lon1, double lat2, double lon2);
  15.  
  16. int main(int argc, char **argv) {
  17.     Json::Value cities;
  18.     // download from http://bulk.openweathermap.org/sample/city.list.json.gz and unzip
  19.     std::ifstream cities_file("city.list.json", std::ifstream::binary);
  20.     cities_file >> cities;
  21.     double query_lat = std::atof(argv[1]), query_lon = std::atof(argv[2]);
  22.     double dist_min = std::numeric_limits<double>::max();
  23.     std::queue<int> min_indices;
  24.  
  25.     for ( int i = 0 ; i < cities.size() ; i++ ){
  26.         double curr_dist = find_distance(cities[i]["coord"]["lat"].asDouble(), cities[i]["coord"]["lon"].asDouble(), query_lat, query_lon);
  27.  
  28.         if ( curr_dist < dist_min ) {
  29.             dist_min = curr_dist;
  30.             min_indices.push(i);
  31.             if ( min_indices.size() > 5 )
  32.                 min_indices.pop();
  33.         }
  34.     }
  35.  
  36.     while ( !min_indices.empty() ) {
  37.         int min_index = min_indices.front();
  38.         std::cout << cities[min_index]["id"] << std::endl;
  39.         std::cout << cities[min_index]["name"] << " " << cities[min_index]["country"] << std::endl;
  40.         min_indices.pop();
  41.     }
  42.    
  43.     return 0;
  44. }
  45.  
  46. double find_distance(double lat1, double lon1, double lat2, double lon2) {
  47.     static double rad_per_deg = std::acos(0) / 90.0;
  48.     lat1 *= rad_per_deg;
  49.     lon1 *= rad_per_deg;
  50.     lat2 *= rad_per_deg;
  51.     lon2 *= rad_per_deg;
  52.  
  53.     //ref: https://wp.me/p7skFn-8S for derivation of find_distance
  54.     return std::acos(std::sin(lat1) * std::sin(lat2) + std::cos(lat1) * std::cos(lat2) * std::cos(lon1 - lon2));
  55. }
Advertisement
Add Comment
Please, Sign In to add comment