We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 21017
    • 3 Posts
    I would build a query that returns a set of resources from the db and sorts them based on distance from a given location. Every resource have lat & lng TV.
    Do you have any idea how could I acheive the sample statement below useing by xPDO?

    SELECT *,
        SQRT(POW((69.1 * (resources.latitude - 27.950898)) , 2 ) +
        POW((53 * (resources.longitude - -82.461517)), 2)) AS distance
    FROM resources
    ORDER BY distance ASC
    LIMIT 5
      • 22303 MODX Staff
      • 10,725 Posts
      Something like this should do what you want:

      <?php
      $query = $modx->newQuery('modResource');
      $query->join('modTemplateVarResource', 'lat', array('tmplvarid' => $tvLat, "lat.contentid = modResource.id"));
      $query->join('modTemplateVarResource', 'lng', array('tmplvarid' => $tvLng, "lng.contentid = modResource.id"));
      $query->select($modx->getSelectColumns('modResource', 'modResource', 'modResource_'));
      $query->select(array(
          'distance' => "SQRT(POW((69.1 * (lat.value - 27.950898)) , 2 ) + POW((53 * (lng.value - -82.461517)), 2))"
      ))
      $query->sortby('distance', 'ASC');
      $query->limit(5);
      
      $resources = $modx->getCollection('modResource', $query);