Handling Addresses and Locations in Drupal 7

In the good old Drupal 6 days, when you had to store an address and have that address converted into a latitude and longitude you would use the Location module. If you wanted to display a Google Map on your website, you would use the Gmap Module. In Drupal 7 the landscape has changed and now you have a lot options than just using the Location module.

A lot of the functionality that Location module gives you can be found in separate modules indicated in Table 1-0.

Table 1-0. Location based modules

Module Details
Address Field Custom field that allows you to store addresses.
Geofield Allows you to store geographic data in a number of formats.
GeoPHP Provides Drupal integration with the geoPHP library.
Geocoder Converts a postal address into a geographic data.

In this article I’ll show you how to setup the modules mentioned above to allow website users to enter in an address and then have a map displaying the location of the address. You may think that installing four modules to handle addresses and locations is a bit too much. This method does give you some flexibility. Let’s say, for now, you only need to store addresses, but in the future you may want to store coordinates as well. Then, just setup Address Field to handle addresses for now and Geofield later.

Getting Started

Before we get started there are a few modules we need to download. Go download and install the following modules:

If you use Drush run the following command to download the required modules:

$ drush dl addressfield geophp geofield geocoder

Using Address Field and Geofield

Now that we have downloaded and installed all the required modules, let’s go ahead and setup our fields. For this article I have created a Venue content type which I’ll use throughout this article.

How To

1. Go to Structure -> “Content types” (admin/structure/ types) and click the “manage fields” link on a specific content type. Create an Address Field using the settings defined in Table 1-1.

Table 1-1. Define an address field

Option Value
Label Address
Machine name field_venue_address
Field type Postal address
Widget Dynamic address form

2. Click on the Save button to create the field, on the “Field settings” page click on the “Save field settings” button. Configure the address field if you need to, then click on “Save settings” to return to the “manage fields” page.

The field that we created above will be used to store the human readable postal address. The entered address could be displayed anywhere on the site. The next field we’ll create will store the coordinates for the entered postal address, we’ll use the Geofield module for this field.

3. Make sure you’re in the “manage fields” page and create a Geofield using the settings defined in Table 1-2.

Table 1-2. Define a Geofield field

Option Value
Label Location
Machine name field_venue_location
Field type Geofield
Widget Geocode from another field

If you don’t see the “Geocode from another field” widget, make sure you have downloaded and installed the Geocoder module.

4. Click on the Save button to create the field, on the “field settings” page click on the “Save field settings” button. Change the “Geocode from field” drop-down to Address.

5. Scroll to the bottom of the page and click on “Save settings”.

6. Now go a head and test everything. When you enter in an address the Location field should automatically be populated with coordinates.

Map Display

At this point we have a content type called Venue where we store an address and coordinates. Currently the location field is just displaying coordinates, that’s a bit useless. Let’s display a map interface instead. Go to the Modules page and enable “Geofield map” module. This module – which ships with Geofield – simply offers a basic map interface.

How To

1. Go to Structure -> “Content types” (admin/structure/ types) and click the “manage display” link on a specific content type. Change the Format for the Location field to “Geofield map”.

2. Configure the formatter if you have to, then click on Save.

3. Go back to your test content and you should see a map instead of coordinates.

Conclusion

It’s important to understand that there is always a few different ways to do location in Drupal and this is just one way. Do some research and don’t forget to review other modules.

Here’s a list of other modules:

If you have any questions please leave a comment.

Further Resources

56 thoughts on “Handling Addresses and Locations in Drupal 7”

  1. Hi , IT’s excellent your tutorial , but I have a question, how can I show more than 1 point in the geo map ?

    Thanks

    1. Good question. I have always created a custom map if I had to display multiple markers. Try changing the “Number of values” value to something greater than 1. See if that works.

  2. This is a really good and well written tutorial. It worked a treat. I’m building a site which displays landlord reviews from renters. Thanks a lot!!

  3. is there any way we can reverse populate address field fields in D7,
    user gets the coordinates from another field, can we populate addressfield fileds?

    1. Good question, honestly I don’t know.

      I would first see if there is an API for converting lat/lng to an address. If there is an API, you could do it with custom code.

      If you find a module let me know.

  4. I followed the above steps, but I get the following error when viewing my page :

    Exception: Cannot construct Point. x and y should be numeric in Point->__construct() (line 23 of /sites/all/modules/geophp/geoPHP/lib/geometry/Point.class.php).

    I tried but the last stable and the current dev version of the geoPHP module, but no change. Any idea ?

    1. On which page are you getting the error. On a node page (node/234)? or when you edit a node?

      Also which modules did you install?

      1. I’m on a node page. Editing gives me no errors.

        I have the following nodes installed related to this :

        Address Field 7.x-1.0-beta3
        Geocoder 7.x-1.2
        Geofield 7.x-1.1
        Geofield Map 7.x-1.1
        geoPHP 7.x-1.7+3-dev

        I have in total 88 modules enabled, not sure if any of thise would interfere

        1. It seems there is a problem with the geoPHP module base off the error.

          geoPHP could be having trouble processing coordinates. Check that the coordinates are being saved properly.

  5. great post, thanks!
    I’m trying to figure out how to have a user click the map and get the data into a CT.
    this way user don’t need address, and things are easier.

    any ideas?

    1. Sorry, I don’t know how to do that in Drupal 7. In Drupal 6, the Location module allowed you to place a marker directly on a map.

      Let me know how you go.

  6. Dear Ivan,
    thanks for the very useful tutorial. It works on Drupal 7.19 but the new release 7.20
    Can you, please check with this new Drupal version.
    Thanks! Agio

        1. I just tested the tutorial on a fresh installation of Drupal 7.20 and everything worked.

          Are there any JavaScript or PHP errors?

          1. Thanks to your prompt feedbacks, now it is working!
            I repeated the Drupal version update procedure and now it is all fine (probably I made some mistakes in this before).

            Thanks again
            Agio

  7. awesome. after a long time i tried now the third time to work with maps and adress fields – and after these i find out how it works. thanks mate for that.

  8. Hi Ivan,
    I am implementing a Drupal 7 signup form (through a custom module) where users should be able to indicate their location (Country + Province/State) using dropdown lists. From the description of Location module, this seems possible. I am new to Drupal and have no idea of how to implement this in the custom module programatically (using location module’s APIs). I’ve googled about this for a couple of days, but couldn’t make much progress.

    Could you please help me?

    Any sample code or leads would be greatly appreciated.

    Thanks a Ton.
    RJ

    1. Sorry I don’t have any code examples, but that functionality “should” be exposed as an API. I would reverse engineer the Location module to find those API functions.

      1. Thanks for the reply. :). BTW awesome tutorials. I like the your step by step approach to teach a concept with the screen shots.

  9. David Newkerk

    Worked like a charm! Past experience with Location module made me think to see what other options the Drupal community had cooked up since then. After an hour or so of searching and reading, I found the sheer number of location/map related modules challenging to sift through and figure out which to use and how to wire them together. This was a perfect, right to the point guide that made everything clear and got me up in running in a matter of minutes. Thanks!

  10. It doesn’t work in a fresh installation 7.22 drupal.
    The map is not showing when i chose “geocoder from another field” en the geofield widgets
    It seems no associate boths champs: geofield and adressfield…
    But it’s work ok when i chose “html5 geolocation, wkt, etc…”

    I use :
    addressfield-7.x-1.0-beta4
    geophp-7.x-1.7
    geocoder-7.x-1.2
    geofield-7.x-1.1

    1. The “geocoder from another field” widget does not display a map. It simply converts an address to geographical coordinates.

      The “Geofield map” formatter is what displays the map.

      1. yes, sorry i wasn’t clear in my question ( my english is very bad):

        the geographical coordinates doesn’t appear when i chose “geocoder from another field”. And of course when i choose “geofield map” formatter the map is hidden also.

        it’s very strange: when i change the widget and i choose “html5 geolocation” everything works fine. After a day working with “html5 geolocation” i change the widget again ant choose “geocoder from another field” + “Geofield map” formatter, this time everything seems ok.

        I combined this tuto width leaflet module, the maps are very beautiful!

        Thank you very much

  11. Thanks so much for this; absolutely brilliant. Had been tinkering around with Location and GMap – but had absolutely no luck when it came to centering the map. This one does it automagically.

    1 question though… I’ve added the field to the user entity. How would I go about creating locations for old entries? It’s done for new entries as well as entries that are updated manually.

    Thanks in advance.

    1. Good question, but I don’t think there is a simple solution.

      You should be able to do this with custom code. Write a bit of code that loads the user object and then saves it.

      Or, look at using Rules (http://drupal.org/project/rules) to load and save user objects.

    2. Same problem here. Looking to implement something in cron so it can gradually catch up without running into the Google geocode limits.

  12. Great!! Tutorial , i had created a map in just couple of clicks. but i also Wants to show list of users near by location, or any other criteria in between that users.
    Have any solution??

  13. Great tutorial – thanks!
    Sadly I had already imported all of my content before my client decided to add mapping.
    In case anyone else encounters this – it seems you’ll need to open and re-save each content piece in order to get GeoCoder to generate the coordinates. In my case fortunately I have only 44 locations.
    I suppose a re-import using Feeds Import or Migrate might work, if anyone has a lot of nodes to map.

    1. Unfortunately there is no quick solution. The simplest way would be to re-import nodes using Feeds or Migrate.

  14. Sadanand Kenganal

    Sir,

    I want to search location that should display in map not in text results. How can i do it using views and maps. Search field is location or address. Based on the address field or location field it will display map. Please hel me!!!

  15. Nikolay Stoynov

    This always seems to get the wrong location for me. I have to play around a lot until get the real location. For example I want to show “27 bulevard ‘Tsar Osvoboditel'” – set city to Varna, Bulgaria, and it goes me on the city’s dump yard. I have to change the address to “27 bulevard ‘Tsar Osvoboditel’ – Varna” to get me the proper location. Is there a way to edit the location from address field without going commando?

    1. I have to play around a lot until get the real location.

      Are you referring to the geocoded location? That is handled by the selected geocoding service.

      Address field simply stores an address.

      1. As far as my understanding goes, geocoding service uses the values from Address field to generate map. In some cases there are multiple results for that, or simply it points elsewhere. Is there a way to include latitude/longitude field to Address field, so if map is wrong to specify exact coordinates I want it pointing. I’ve seen lat/long only maps, but I want to use physical address if possible.

  16. You can use the following code (with smart_ip and geophp) to reverse geocode latlong: $longitude = $_SESSION[‘smart_ip’][‘location’][‘longitude’];
    $latitude = $_SESSION[‘smart_ip’][‘location’][‘latitude’];
    geophp_load();
    $json = ‘{
    “type”: “Point”,
    “coordinates”: [‘ . $longitude . ‘,’ . $latitude . ‘]
    }’;
    $myaddress = geoPHP::load($json,’json’)->out(‘google_geocode’);
    drupal_set_message($myadress);

  17. I implemented this several months ago on a site and it all works well . but suddenly when a new property is set up with a new location, the location coordinates are not being created .. therefore, the new location does not show on the map. Why would this functionality just stop working?

    1. If your maps are not appearing it could be that addresses are not being geocoded. Check and see if coordinates are being stored in the database. Also, have you updated one of the location modules recently (geofield geocoder)?

      Unfortunately, there is no silver bullet when debugging this type of issue.

  18. I’m over the Google query limit. Found this in my error report:

    Exception: Google API returned bad status.\nStatus: OVER_QUERY_LIMIT in geocoder_google() (line 52 of /home/robertlj/public_html/sites/all/modules/geocoder/plugins/geocoder_handler/google.inc).

    What is the best way around this? What I sent you the link to is one of three maps on the site that do the same thing for different kinds of properties, so I have to be able to populate these maps with new properties.

    Any thought?

    Many thanks!
    Nancy

  19. Hello!

    First thank you for another great tutorial. I have one question concerning the map. When I click over the red pointer “contact us:” text appears, but the address is missing. I filled address’s field settings, but it seems that it does not work. Could you please help with this?

    1. Sorry, what is “contact us:” is this the node title? I never covered adding content into the info box in this tutorial.

      Look at using OpenLayers or Leaflet to create a custom map and then you should be able to modify the info box.

Comments are closed.