doublesecretagency / craft-googlemaps

Google Maps plugin for Craft CMS - Maps in minutes. Powered by the Google Maps API.
https://plugins.doublesecretagency.com/google-maps/
Other
10 stars 8 forks source link

How to perform proximity searches on related elements? #38

Closed aaronbushnell closed 2 years ago

aaronbushnell commented 2 years ago

We have a unique setup in that we have Buildings and Locations. Our building entries house the Google Map field and many locations can exist within the building. Here's the schema:

BUILDING
- Title
- Address (Google Maps)

LOCATION:
- Title
- Building (Entries; single select relationship)

Because of this setup I cannot perform a proximity search on "Locations" as the Google Map field doesn't exist on this entry type:

{% set params = { 'target': 'chicago', radius: 100 } %}

{% set locations = craft.entries.section('location').address(params).orderBy('distance').all() %}

Any recommendations on the best way to achieve this type of proximity search where the address field exists on a related entry?

Thanks!

lindseydiloreto commented 2 years ago

I'd recommend running the proximity search on the Buildings section directly, since that's where the Address field is.

Then work backwards from there...

{# Get all buildings, sorted by distance #}
{% set buildings = craft.entries.section('building').address(params).orderBy('distance').all() %}

{# Loop through results #}
{% for building in buildings %}

    {# Get each building location #}
    {% set location = craft.entries.relatedTo(building).one() %}

    {# ... then whatever you want #}

{% endfor %}

I admit it may get a little interesting with multiple Buildings sharing the same Location. You may need to do some fancy juggling of Twig data to minimize any repetitive DB queries.

Hope that helps! Feel free to hit me up on Discord if you get stuck on the details. 🙂

aaronbushnell commented 2 years ago

Thanks, @lindseydiloreto!