2017 © Pedro Peláez
 

library laravel_cities

Seed all countries/cities from geonames.org database. Searchable DB tree, ready to use API & a bonus vue.js component!

image

awkwardideas/laravel_cities

Seed all countries/cities from geonames.org database. Searchable DB tree, ready to use API & a bonus vue.js component!

  • Thursday, May 10, 2018
  • by awkwardideas
  • Repository
  • 1 Watchers
  • 1 Stars
  • 3 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 17 Forks
  • 0 Open issues
  • 11 Versions
  • 50 % Grown

The README.md

Laravel License, (*1)

Forked from igaster/laravel_cities

Introduction

  • Deploy and use geonames.org (ex MaxCDN) database locally to query countries/cities
  • Includes latitude/longitude
  • Optimized DB tree structure for searching and traversing the tree.
  • Provides an Eloquent model (geo) with multiple query-scopes to help you build your queries.
  • Exposes a simple API that you can use to create AJAX calls. (Eg search while typing etc).
  • A sample vue.js component that that can be inserted into your forms and provides a UI to pick a location

What you dont get: - geoIP & Postalcodes (not included in free sets) - Map elements smaller than "3rd Administration Division" (=Cities), (*2)

Instructions

  • Install with copmoser. Run:

composer require awkwardideas/laravel_cities, (*3)

  • Add Service Provider in app.php:
'providers' => [
    //...
    AwkwardIdeas\LaravelCities\GeoServiceProvider::class,
];
  • Create a folder geo into app's storage folder ('\storage\geo'). Download & unzip "hieararcy.txt" & "allCountries.txt" from geonames.org (http://download.geonames.org/export/dump)

[Tip] Quick script to download on your remote server with:, (*4)

mkdir storage/geo
cd storage/geo
wget http://download.geonames.org/export/dump/allCountries.zip && unzip allCountries.zip && rm allCountries.zip
wget http://download.geonames.org/export/dump/hierarchy.zip && unzip hierarchy.zip && rm hierarchy.zip
  • Migrate and Seed. Run:
php artisan migrate
php artisan geo:seed

Note: If you don't want all the countries, you can download only country specific files (eg US.txt) and import each one of them with:, (*5)

php artisan geo:seed US --append

Seed with custom data

Create a json file with custom data at storage\geo and run the following command to pick a file to seed:, (*6)

php artisan geo:json

If an item exists in the DB (based on the 'id' value), then it will be updated else a new entry will be inserted. For example the following json file will rename United States to USA and it will add a child item (set by the parent_id value), (*7)

[
  {
    "id": 6252001,
    "name": "USA"
  },
  {
    "name": "USA Child Item",
    "parent_id": 6252001,
    "lat": "39.760000",
    "long": "-98.500000"
  }
]

Please note that adding new items to the DB will reindex ALL items to rebuild the tree structure. Please be patient..., (*8)

An example file is provided: countryNames.json which updates the official country names with a most popular simplified version., (*9)

Tip: You can get a json representation from the DB by quering the API (see below), (*10)

Geo Model:

You can use AwkwardIdeas\LaravelCities\Geo Model to access the database. List of available properties:, (*11)

$geo->name;       // name of geographical point in plain ascii
$geo->country;    // 2-letter country code (ISO-3166)
$geo->id;         // Original id from geonames.org database (geonameid)
$geo->lat;        // latitude in decimal degrees (wgs84)
$geo->long;       // longitude in decimal degrees (wgs84)
$geo->level;      // Administrator level code (feature code)
// parent_id, left, right, depth: Used to build hierarcy tree

Visit http://www.geonames.org > Info, for a more detailed description., (*12)

Usage

Searching:

use AwkwardIdeas\LaravelCities\Geo;

Geo::getCountries();               // Get a Collection of all countries
Geo::getCountry('US');             // Get item by Country code
Geo::findName('Nomos Kerkyras');   // Find item by (ascii) name
Geo::searchNames('york');          // Search item by all alternative names. Case insensitive 
Geo::searchNames('vegas', Geo::getCountry('US'));  // ... and belongs to an item
Geo::getByIds([390903,3175395]);   // Get a Collection of items by Ids

Traverse tree

$children    = $geo->getChildren();    // Get direct Children of $geo (Collection)
$parent      = $geo->getParent();      // Get single Parent of $geo (Geo)
$ancenstors  = $geo->getAncensors();   // Get Ancenstors tree of $geo from top->bottom (Collection)
$descendants = $geo->getDescendants(); // Get all Descentants of $geo alphabetic (Collection)

Check Hierarchy Relations:

$geo1->isParentOf($geo2);       // (Bool) Check if $geo2 is direct Parent of $geo1
$geo2->isChildOf($geo1);        // (Bool) Check if $geo2 is direct Child of $geo1
$geo1->isAncenstorOf($geo2);    // (Bool) Check if $geo2 is Ancenstor of $geo1
$geo2->isDescendantOf($geo1);   // (Bool) Check if $geo2 is Descentant of $geo1

Query scopes (Use them to Build custom queries)

Geo::level($level);     // Filter by Administration level: 
                        // Geo::LEVEL_COUNTRY, Geo::LEVEL_CAPITAL, Geo::LEVEL_1, Geo::LEVEL_2, Geo::LEVEL_3
Geo::country('US');     // (Shortcut) Items that belongs to country US 
Geo::capital();         // (Shortcut) Items that are capitals
Geo::search($name);     // Items that conain $name in name OR alternames (Case InSensitive)
Geo::areDescentants($geo);   // Items that belong to $geo

$geo->ancenstors();     // Items that contain $geo
$geo->descendants();    // Items that belong to $geo
$geo->children();       // Items that are direct children of $geo


//--Scope usage Examples:

// Get the States of USA in aplhabetic order
Geo::getCountry('US')
    ->children()
    ->orderBy('name')
    ->get();

// Get the 3 biggest cities of Greece
Geo::getCountry('GR')
    ->level(Geo::LEVEL_3)
    ->orderBy('population','DESC')
    ->limit(3)
    ->get();

If you need more functionality you can extend AwkwardIdeas\LaravelCities\Geo model and add your methods., (*13)

HTTP API

This package defines some API routes that can be used to query the DB through simple HTTP requests. To use them insert in your routes file:, (*14)

\AwkwardIdeas\LaravelCities\Geo::ApiRoutes();

For example if you insert them in your routes\api.php (recommended) then the following URLs will be registered:, (*15)

URL Endpoind (GET) Description Returns (JSON)
api/geo/search/{name}/{parent-id?} Search items containing 'name', (and belong to parent-id) Collection
api/geo/item/{id} Get item by id Geo
api/geo/items/{ids} Get multiple items by ids (comma seperated list) Collection
api/geo/children/{id} Get children of item Collection
api/geo/parent/{id} Get parent of item Geo
api/geo/country/{code} get country by two-letter code Geo
api/geo/countries list of countries Collection

The response is always a JSON representation of either a Geo class or a Collection., (*16)

To reduce bandwith, all Geo model attributes will be returned except from alternames, left, right and depth. You can change this behavior by passing an optional parameter on any request:, (*17)

URL Params (aplly to all routes) Description Example
fields=field1,field2 Returns only the specified attributes api/geo/countries?fields=id,name
fields=all Returns all attributes api/geo/countries?fields=all

Vue Component

A Vue component is shipped with this package that plugs into the provided API and provides an interactive way to pick a location through a series of steps. Sorry, no live demo yet, just some screenshots:, (*18)

Step 1: Select your location. Drop down lists loads asynchronous:, (*19)

Select Location, (*20)

Step 2: Reached to a destination. Path is displayed and button to edit selection:, (*21)

Finished Selection, (*22)

Step 3: On form submition several fields are beeing submited:, (*23)

Form Submited, (*24)

Usage Guide

Assuming that you are using Webpack to compile your assets, and you have included vue-app.js:, (*25)

Add in your application

In your main vue-app.js file add the component declaration:, (*26)

Vue.component('geo-select', require('RELATIVE_PATH_TO/vendor/awkwardideas/laravel_cities/src/vue/geo-select.vue'));, (*27)

Alternative you may publish the component with, (*28)

artisan vendor:publish --provider="AwkwardIdeas\LaravelCities\GeoServiceProvider", (*29)

Component will be exported at /resources/LaravelCities/geo-select.vue so that you can make modifications..., (*30)

If you choose to do the exported component, make sure you register it in the vue-app.js file with, (*31)

Vue.component('geo-select', require('RELATIVE_PATH_TO/resources/LaravelCities/geo-select.vue'));, (*32)

Compile compoment

npm run dev (or npm run production), (*33)

Use in blade files

Example:, (*34)

<form action="post-url" method="POST">
    <geo-select></geo-select>
    <!-- Add more form fields here... -->
    <input type="submit">
</form>

The following inputs will be submited:, (*35)

  • geo-id
  • geo-name
  • geo-long
  • geo-lat
  • geo-country
  • geo-country-code

Full syntax:

<geo-select
    prefix = "geo"                    <!-- change the  fields name prefix --> 
    api-root-url = "\api"             <!-- Root url for API -->
    :countries = "[390903,3175395]"   <!-- Limit to specific countries (defined by ids) -->
    :enable-breadcrumb = "true"       <!-- Enable/Disable Breadcrumb -->
></geo-select>

The Versions

10/05 2018

dev-master

9999999-dev https://github.com/awkwardideas/laravel_cities.git

Seed all countries/cities from geonames.org database. Searchable DB tree, ready to use API & a bonus vue.js component!

  Sources   Download

MIT

The Requires

 

The Development Requires

by Chad Haney
by Awkward Ideas
by Giannis Gasteratos

laravel geolocation countries cities geonames.org

05/05 2018

v1.4.0

1.4.0.0 https://github.com/awkwardideas/laravel_cities.git

Seed all countries/cities from geonames.org database. Searchable DB tree, ready to use API & a bonus vue.js component!

  Sources   Download

MIT

The Requires

 

The Development Requires

by Chad Haney
by Awkward Ideas
by Giannis Gasteratos

laravel geolocation countries cities geonames.org

12/02 2018

v1.3.2

1.3.2.0 https://github.com/igaster/laravel_cities.git

Seed all countries/cities from geonames.org database. Searchable DB tree, ready to use API & a bonus vue.js component!

  Sources   Download

MIT

The Requires

 

The Development Requires

by Giannis Gasteratos

laravel geolocation countries cities geonames.org

19/09 2017

v1.3.1

1.3.1.0 https://github.com/igaster/laravel_cities.git

Seed all countries/cities from geonames.org database. Searchable DB tree, ready to use API & a bonus vue.js component!

  Sources   Download

MIT

The Requires

 

The Development Requires

by Giannis Gasteratos

laravel geolocation countries cities geonames.org

19/04 2017

v1.3

1.3.0.0 https://github.com/igaster/laravel_cities.git

Seed all countries/cities from geonames.org database. Searchable DB tree, ready to use API & a bonus vue.js component!

  Sources   Download

MIT

The Requires

 

The Development Requires

by Giannis Gasteratos

laravel geolocation countries cities geonames.org

31/03 2017

v1.2.2

1.2.2.0 https://github.com/igaster/laravel_cities.git

Find any country/city in the world. Get Long/Lat etc. Deploy geonames.org database localy. Optimized DB tree structure

  Sources   Download

MIT

The Requires

 

The Development Requires

by Giannis Gasteratos

geolocation countries cities laravel-5.x geonames.org

30/03 2017

v1.2.1

1.2.1.0 https://github.com/igaster/laravel_cities.git

Find any country/city. Deploy geonames.org database localy. Find lang/lat etc. Optimized DB tree structure

  Sources   Download

MIT

The Requires

 

The Development Requires

by Giannis Gasteratos

laravel-5.x geonames.org