Province/State sorting issues with Views and Location modules

April 22nd, 2011
by Brian

The Location module for Drupal is handy for collecting addresses and for geocoding that information for use with Google maps (see GMap module), but we recently ran into an issue where the ordering was incorrect if we had a View that was sorted by Location:Province (or state here in the US). It seems that the Location module sorts the View results by state code instead of state name. 

Above is a quick look at our View's preview results. Massachusetts before Maryland? North Carolina before Nebraska and New York? What kind of sorting is that? It makes more sense if you think of it as MA before MD, and NC before NE and NY. But since we are not displaying the state codes, we don't want it to sort by them.

We got some help from the user philipz who wrote a post regarding the same sorting issue, but with country instead of province. His code served as a starting point from which we made a custom module that will sort the province/state alphabetically by full name and not it's abbreviated code.

The code as it was written had one issue that needed to be fixed for our purposes as well. If used as is the code would only displaying a single result for any given country (or province/state in our case) due to the way the associative array was being written. To fit our needs we made the key for each value in the array less generic, modifying this:

$provinces[location_province_name($view->result[$i]->location_country, $view->result[$i]->location_province)] = $i; this:

$provinces[location_province_name($view->result[$i]->location_country, $view->result[$i]->location_province) . "-" . $view->result[$i]->node_title] = $i;

By adding specific information, like node_title, to each indexed item, we ensured that the previous item would not be overwritten. Before making this change, only the last item for a given province/state would be displayed, because it was overwriting the previous entry in the array with the same generic key.

After enabling this new module, the View's results were alphabetized by province/state name, as we had originally wanted.


If you have a similar need you can download the module we used here.

Posted in drupal, drupal, issues, location, modules, views, web development