Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* You must install JSONCpp library to use this program.
- Compile this file using this command:
- c++ -o nearestcity nearestcity.cc -ljsoncpp
- */
- #include <iostream>
- #include <cstdlib>
- #include <iomanip>
- #include <fstream>
- #include <limits>
- #include <cmath>
- #include <queue>
- #include <json/json.h>
- double find_distance(double lat1, double lon1, double lat2, double lon2);
- int main(int argc, char **argv) {
- Json::Value cities;
- // download from http://bulk.openweathermap.org/sample/city.list.json.gz and unzip
- std::ifstream cities_file("city.list.json", std::ifstream::binary);
- cities_file >> cities;
- double query_lat = std::atof(argv[1]), query_lon = std::atof(argv[2]);
- double dist_min = std::numeric_limits<double>::max();
- std::queue<int> min_indices;
- for ( int i = 0 ; i < cities.size() ; i++ ){
- double curr_dist = find_distance(cities[i]["coord"]["lat"].asDouble(), cities[i]["coord"]["lon"].asDouble(), query_lat, query_lon);
- if ( curr_dist < dist_min ) {
- dist_min = curr_dist;
- min_indices.push(i);
- if ( min_indices.size() > 5 )
- min_indices.pop();
- }
- }
- while ( !min_indices.empty() ) {
- int min_index = min_indices.front();
- std::cout << cities[min_index]["id"] << std::endl;
- std::cout << cities[min_index]["name"] << " " << cities[min_index]["country"] << std::endl;
- min_indices.pop();
- }
- return 0;
- }
- double find_distance(double lat1, double lon1, double lat2, double lon2) {
- static double rad_per_deg = std::acos(0) / 90.0;
- lat1 *= rad_per_deg;
- lon1 *= rad_per_deg;
- lat2 *= rad_per_deg;
- lon2 *= rad_per_deg;
- //ref: https://wp.me/p7skFn-8S for derivation of find_distance
- return std::acos(std::sin(lat1) * std::sin(lat2) + std::cos(lat1) * std::cos(lat2) * std::cos(lon1 - lon2));
- }
Advertisement
Add Comment
Please, Sign In to add comment