How to find nearest cities in a given radius?

前端 未结 6 1907
遇见更好的自我
遇见更好的自我 2020-12-31 15:41

Do you know some utility or a web site where I can give US city,state and radial distance in miles as input and it would return me all the cities within that radius?

<
6条回答
  •  不知归路
    2020-12-31 16:36

    Maybe this can help. The project is configured in kilometers though. You can modify these in CityDAO.java

    public List findCityInRange(GeoPoint geoPoint, double distance) {
        List cities = new ArrayList();
        QueryBuilder queryBuilder = geoDistanceQuery("geoPoint")
                .point(geoPoint.getLat(), geoPoint.getLon())
                //.distance(distance, DistanceUnit.KILOMETERS) original
                .distance(distance, DistanceUnit.MILES)
                .optimizeBbox("memory")
                .geoDistance(GeoDistance.ARC);
    
        SearchRequestBuilder builder = esClient.getClient()
                .prepareSearch(INDEX)
                .setTypes("city")
                .setSearchType(SearchType.QUERY_THEN_FETCH)
                .setScroll(new TimeValue(60000))
                .setSize(100).setExplain(true)
                .setPostFilter(queryBuilder)
                .addSort(SortBuilders.geoDistanceSort("geoPoint")
                        .order(SortOrder.ASC)
                        .point(geoPoint.getLat(), geoPoint.getLon())
                        //.unit(DistanceUnit.KILOMETERS)); Original
                        .unit(DistanceUnit.MILES));
    
        SearchResponse response = builder
                .execute()
                .actionGet();
    
    
        SearchHit[] hits = response.getHits().getHits();
    
        scroll:
        while (true) {
    
            for (SearchHit hit : hits) {
                Map result = hit.getSource();
                cities.add(mapper.convertValue(result, City.class));
            }
    
            response = esClient.getClient().prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
            if (response.getHits().getHits().length == 0) {
                break scroll;
            }
        }
    
        return cities;
    }
    

    The "LocationFinder\src\main\resources\json\cities.json" file contains all cities from Belgium. You can delete or create entries if you want too. As long as you don't change the names and/or structure, no code changes are required.

    Make sure to read the README https://github.com/GlennVanSchil/LocationFinder

提交回复
热议问题