从JAVA提取MongoDB“NYC餐馆”系列中的地理位置字段

时间:2016-05-28 13:37:12

标签: java mongodb geolocation

我在MongoDB中使用纽约餐馆的数据集。每个餐厅都有这样一个地址:

"address" : { 
    "building" : "461", 
    "coord" : [-74.138492, 40.631136],
    "street" : "Port Richmond Ave", 
    "zipcode" : "10302"
}

我试图通过Java代码将"coord"作为double对 - 它不适用于List。这个数据结构是什么[-74.138492, 40.631136]?我只想将餐厅坐标与我的位置进行比较,找到特定范围内的所有餐厅。

1 个答案:

答案 0 :(得分:0)

与此同时,我找到了获得" coord"的方法。字段为double。代码远非完美。如果有人知道更优雅的方式来做到这一点 - 我很高兴知道。 " closestPoints"是一种计算我所在位置周围定义范围框的方法。同时它只打印出过滤后的坐标。

// ....一些代码......

    DB db = mongoClient.getDB("test");
    DBCollection coll = db.getCollection("restaurants");

    BasicDBObject query = new BasicDBObject();

    query.put("cuisine", "Chinese");

    DBCursor cursor = coll.find(query);

    //coordinates for box of defined range around my location.
    double lat1 = myPoint.closestPoints(1)[0];
    double lat2 = myPoint.closestPoints(1)[1];
    double lon1 = myPoint.closestPoints(1)[2];
    double lon2 = myPoint.closestPoints(1)[3];

    try {

        while(cursor.hasNext()) {

        BasicBSONObject addressObj = (BasicBSONObject) cursor.next().get("address");
        BasicDBList addressList = (BasicDBList) addressObj.get("coord");

         double restLongitude  = (double) addressList.get(0);
         double restLatitude = (double) addressList.get(1);

        if ((restLatitude < lat2 && restLatitude > lat1) && (restLongitude < lon2 && restLongitude > lon1)) {
          System.out.println(restLatitude + "," + restLongitude + " box LAT is " + lat1 + ", " + lat2 + " box LON is " + lon1 + "," + lon2 );
        }

    }
    } catch (NullPointerException e) {

        System.err.println("NullPointerException: " + e.getMessage());

    } finally {
      cursor.close();
    }

 mongoClient.close();

// ...一些代码...