Plugin to Upload Arcgis File in Wordpress

WordPress Plugin evolution - Enable spatial capabilities

This tutorial will give an introduction into enabling WordPress with spatial capabilities via a custom plugin and expose those functionalities via the built-in REST API.

It will make use of the splendid WP GeoMeta plugin past Michael Moore. It hasn't been maintained for a while, nonetheless it's even so running strong with the newest WordPress version (5.2.10 at the time of writing). Information technology volition serve as the basis for the plugin you'll develop.

Note, that the terminal result of this tutorial is only useful if you deploy WordPress as a backend and use a frontend framework (e.k. React, AngularJS) to admission WordPress via its Rest API, encounter also Motivation. However, the steps included to get to the final result can too exist helpful when using WordPress as frontend.

The terminal plugin can be found in our tutorial repository.

GeoMeta Plugin example WP GeoMeta Plugin example with a bunch of polygons

Motivation

WordPress is powerful. Very powerful. Most people merely know it for its fool-proof CMS capabilities to build blogs and websites. However, unless you want to build static sites, WordPress is actually not a good solution. For more complex and/or dynamic websites proper frontend frameworks, similar React or AngularJS, are a far better option. Only even then in that location's no demand to ditch WordPress.

Its existent power lies in its backend. WordPress core provides complete user management out-of-the-box and mighty plugins like WooCommerce make very complex web shop setups a cakewalk. And the all-time matter: it all comes with a well-documented and reeeaaally easily extendable Rest API. Y'all start to see its existent merits?

However, we're immediately missing spatial capabilities and likely you are too, if you landed here. What if you want to query the geographical location of users (provided you accept their locations)? Or what if you set up a spider web store for vector print maps and want to query your WooCommerce shop by bounding box to intersect the map products bachelor inside the lateral extent of a spider web map app (Spoiler: that's how we actually got here!)? Fear not, read on and learn how to exercise just that. All contained within your very own WordPress installation, no PostGIS server and even fully functional on shared hosts.

Goals:

  • Become familiar with the WP GeoMeta Plugin past Michael Moore
  • Create a WordPress plugin from scratch
  • Extend existing WordPress REST API routes with new fields
  • Extend WordPress REST API with custom routes
  • Add ST_Intersects functionality to WordPress

Plugin functionality:

You lot will create a custom road with the WordPress REST API, which volition be able to receive a bounding box and return a list of users which are located within this bounding box.

Disclaimer

Validity only confirmed for Ubuntu xviii.04 and WordPress <= v5.2.1

Prerequisites

  • WordPress >= v5.0.0
  • MySQL >= 5.7
  • Basic understanding of WordPress and ideally PHP

1 General setup

Your WordPress installation tin exist remote on a server or local and natively on the host or in a Docker container. That's entirely up to you. However, we do recommend doing information technology locally with Docker, as you'll demand to do quite a bit of PHP programming in the wp-content/plugins binder. So yous'll need the files offline, plus you don't want to litter your precious environs with the likes of PHP 😉

For convenience, we include a docker-compose.yml which you can run to setup a blank-metal WordPress installation and exposes the wp-content directory, and then you tin can outset developing instantly with the IDE of your choice. Upon docker-compose up -d, a new directory ./wp-content will be available, which contains almost WordPress files and most chiefly the plugins directory.

To be able to develop in this directory, you lot'll need to change the permissions of wp-content: sudo chmod -R 777 wp-content (no worries, it's simply localhost!).

WordPress is now bachelor on http://localhost:8090. If y'all oasis't done then already, go through the installation process now. Once installed, you need to change the permalinks settings to enable "normal" access to the Residuum API. In SettingsPermalinks, switch to the Post proper name URL structure. Just to see if it works, call http://localhost:8090/wp-json, which should give you the full API specifications.

two WP GeoMeta Plugin

Michael Moore developed this plugin back in 2017 when he presented it on the Boston 2017 FOSS4G conference. Since then it's unfortunately been fairly quiet on the projection. Withal, information technology's still live and boot on WordPress v5.2.10. So, let's become started.

Details

The GeoMeta plugin enables your WordPress installation to save and query spatial features. This is non really helpful unless in that location are other plugins making use of this functionality. This is what you'll do during this tutorial.

GeoMeta Plugin enables other plugins to:

  • insert spatial data in spatially enabled tables via WordPress meta queries
  • employ spatial functions to query the spatial tables via WordPress meta queries, too passing geometries as arguments

TL;DR Upon installation, information technology creates 4 new databases which are spatially enabled and complement their respective WordPress meta counterparts with a _geo extension in the table name:

  • wp_commentmeta_geo: Holding spatial metadata for the comment table.
  • wp_postmeta_geo: Property spatial metadata for the posts table.
  • wp_termmeta_geo: Holding spatial metadata for the term table.
  • wp_usermeta_geo: Belongings spatial metadata for the users tabular array. This one you'll use in this tutorial.

And then, you see, information technology's only mimicking the meta tables. Those are the tables which shop all kinds of additional information nearly their core counterparts. E.g. the core wp_users table only stores the bones information like email, login proper name, hashed password etc. Its meta equivalent wp_usermeta stores uncritical optional information, similar start name, last proper name etc in key and value columns. WP GeoMeta clones that database model to the wp_usermeta_geo table and extends the tabular array with spatial functionality and a spatial alphabetize. That enables the plugin to interact with mutual WP meta queries, which other plugins can utilize to their advantage. WP meta queries request the core features (posts, users etc.) by its related metadata. You'll shortly come across the general meta query syntax and you'll understand improve.

And now comes the magic: WP GeoMeta auto-detects when a plugin inserts a GeoJSON to one of the above meta tables via a WP meta query. Information technology so converts the GeoJSON in its *_geo equivalent table to the information model a WP meta query would await and converts the GeoJSON geometry to the spatial format MySQL understands. Thus you lot can now use all MySQL spatial functions to query posts, users, comments or terms from within other plugins. Dearest it!

Setup

First, clone the plugin repository to ./wp-content/plugins and alter the ownership to apache's www-data user:

            cd            wp-content/plugins  git clone https://github.com/BrilliantPlugins/wp-geometa  sudo chown -R www-data:www-data wp-geometa

Now you can go into your WordPress Administration page and activate the plugin. Upon successful activation, y'all'll see a WP-GeoMeta entry in the Tools menu:

Plugin activate

Notation, if you're having trouble in WordPress activating WP GeoMeta, you probable accept to update its git submodules:

            cd            wp-geometa git submodule update --init --recursive

Usage

If you lot skip over to the UI of the plugin in ToolsWp-GeoMeta, you'll encounter quite a few tabs. A few of them are actually helpful for sanity checks:

Your Data displays a Leaflet map visualizing the information loaded in the database. System Status shows you the current status of your plugin and spatial data. The entries Geo Tables Be! , Geo Tables Indexed! and All Spatial Data Loaded! should all be green, otherwise at that place's a critical problem. Your Functions is a quick reference for the functions your MySQL installation holds available.

In theory, you should be able utilize the Import Data functionality. However, we could not go it working on localhost and doubtable it's using deprecated WordPress functionalities. Anyways, it's of very limited use equally we're aiming to add spatial data through a custom Postal service endpoint, non manually i-by-1.

iii Plugin skeleton

WordPress plugins are far less verbose and intimidating than most other plugin architectures we've seen. Believe us, nosotros didn't have a single inkling about PHP before starting out on this and nosotros managed to go the unabridged job done within two days. Information technology'south unbelievably like shooting fish in a barrel, so kudos to the WordPress cadre team. Astonishing piece of work.

That being said, this section is for sure not a all-time-exercise guide for WordPress plugin development, but rather a working and applied solution.

Setup

Beginning, create a new plugin directory in ./wp-content/plugins with your plugin name (e.chiliad. gis_ops_spatial;)) and give it the right permissions. While you're at information technology, also setup the other necessary folders:

mkdir -p ./wp-content/plugins/gis_ops_spatial/includes/spatial sudo chown -R www-information:www-information ./wp-content/plugins/gis_ops_spatial

Add plugin base

Create a new file in wp-content/plugins/gis_ops_spatial and call information technology gis_ops.php (or any yous like). This volition exist the entrypoint of the plugin and telephone call all other PHP classes you will ascertain:

            <?php            /**                          * Plugin Name: GIS-OPS Spatial                          * Description: Add together spatial functionalities to WordPress and expose API to collaborate with them.                          * Version:     0.0.ane                          *                          * Author:      Nils Nolde                          * Author URI:  https://gis-ops.com                          *                          * Text Domain: gis_ops_spatial                          *                          * @bundle GisOpsSpatial                          */            if            ( !            divers(            'ABSPATH'            ) ) { 	exit;            // Exit if accessed directly            }            define('GISOPS_PLUGIN_PATH',            dirname( __FILE__ ));            // Base api namespace that represents as well the url                          $baseNamespace            =            'gisops/v1';

The header in this file is how yous let WordPress know of its existence. Information technology has to comply with the WordPress header requirements and at the very minimum comprise the entry * Plugin Proper noun: 30.

Later on yous saved the file y'all tin can get dorsum to the WordPress Administration site and activate the (all the same unfunctional) plugin. In the next sections you'll add functionality.

4 Add together location to users

Let's dive into adding a new REST API route. Later on this section, you'll have spatial data in your MySQL wordpress database that you can view in the GeoMeta plugin dashboard. This is ane of the sections that only makes sense if y'all access the WordPress backend from a frontend engineering science.

Hither's the grab though: if you want a painless way to insert data to the user table to quickly testify results, you demand to do things a little differently from what you'd really practise (or we'd recommend) in a product scenario. Those standard WordPress tables are protected confronting unauthenticated API calls to update or insert records. For quite obvious reasons. Since you lot don't want to do deal with WordPress authentication at this signal, nosotros'll show you lot both ways: a bad and hacky style and the way you'd normally get about this.

Add together a new API route - hacky workaround

First, you'll see the hacky style. Note, this is bypassing born WordPress security features and should only be implemented for sit-in.

Add a new file in wp-content/plugins/gis_ops_spatial/includes/spatial, name it gis_ops-spatial-information-wp-api.php and add the following content:

            <?php            /**                          * GIS-OPS Spatial Data Wp Api                          *                          * @package gis_ops_spatial\GisOpsSpatialData                          */            form            GisOpsSpatialData            {            private                          $baseNamespace;            public            function            __construct(              $baseNamespace)     {                          $              this            ->baseNamespace            =                          $baseNamespace;            add_action('rest_api_init',            assortment(                          $              this            ,            'register_routes'));     }            /**                          * Get plugin namespace.                          * @render string                          */            public            function            get_namespace() {            return                          $              this            ->baseNamespace."/spatial";     }            /**                          * Register boundless api routes for WP API v2.                          */            public            function            register_routes() {            register_rest_route(                          $              this            ->get_namespace(),            'user/(?P<id>\d+)',            array(            'methods'            =>            'POST',            'callback'            => [              $              this            ,            'update_user']         ));     }            /**                          * Updater for /spatial/user Post endpoint. Inserts location into user_meta_data.                          *                          * @param WP_REST_Request $request Total request data.                          * @return WP_REST_Response|WP_Error Either user information is returned or HTTP 404                          */            function            update_user(              $request) {                          $user            =            get_user_by('id',                          $request['id']);            if            (              $user) {            update_user_meta(              $asking['id'],            'location',                          $request['location']);            return            new            WP_REST_Response("Successfully added a location to user ".              $user->display_name,            200);         }            else            {            return            new            WP_Error('no_user',            'Invalid User ID',            array('condition'            =>            404));         }     } }

WordPress made the genius design determination to arrive ridiculously easy to extend its functionality. This is commonly done via action and filter hooks, with which you can insert arbitrary functions into cadre WP functions where they will be executed. A comprehensive list is available on Adam Browns's blog, albeit just upward to v5.ane.

In the constructor of the GisOpsSpatialData class, you lot add your custom function register_routes to the WP cadre office rest_api_init as an action, which is responsible for initializing the WP Remainder API.

The register_routes function but calls the core WP office register_rest_route, which will add a custom route to the Rest API. Its arguments are as follows:

  • namespace: this is the the base URL you want this road to exist accessible in, i.eastward. everything which comes in between http://localhost:8090/wp-json/ and the route name. In this class it's built from the plugin'due south base namespace, i.e. gisops/v1 plus /spatial
  • route: the proper name of the route plus optional path parameter(due south). The path parameter follows the pattern (?P<param_name>regex), so you tin can define any regular expression later the parameter proper name. Multiple path parameters are immune. Note, the regular expression has to be valid. And so, in this case the final API route would exist http://localhost:8090/gisops/v1/spatial/user/ane for the first user.
  • args: named array of arguments. It commonly includes the arguments methods and callback:
    • methods: string of comma-separated HTTP methods. E.g. 'Mail,PATCH' or just 'Postal service'
    • callback: the function to exist called when the HTTP method(s) was triggered
    • (options) permission_callback: can be used to determine who's allowed to admission the resource. Usually using WordPress built-in current_user_can(arg) where arg is a WordPress function or capability. In your example, don't specify information technology, every bit the whole point of the hacky workaround is to circumvent authorization.

Then, when our new road receives a POST asking the function update_user is executed. That method takes the full request parameters as input and just inserts the location information every bit-is to the wp_usermeta MySQL table via an update meta query. If the user wasn't constitute, it will return a 404.

Add to plugin skeleton - hacky workaround

For this new functionality to take effect, you need to instantiate the grade in the plugin base. So, you lot crave it in gis_ops.php and create an example. Remember, the constructor of our new class includes a rest_api_init action hook. So, only by instantiating the class you already tell WordPress to add together your custom endpoint.

To do and then, add the post-obit fleck to /wp-content/plugins/gis_ops_spatial/gis_ops.php at the very bottom:

            // Import custom spatial api endpoint classes            require_once            GISOPS_PLUGIN_PATH            .            '/includes/spatial/gis_ops-spatial-data-wp-api.php';            // Instantiate the form                          $gisopsSpatialData            =            new            GisOpsSpatialData(              $baseNamespace);

Try it out - hacky workaround

Finally you tin can see all this actually worked. If y'all didn't do so even so, actuate now your plugin on the WordPress Administration site. And then flip over to your favorite HTTP handler (nosotros recommend Postman, merely curl will also do) and burn against your new endpoint. For convenience, this should work from your concluding:

curl -X POST \   http://localhost:8090/wp-json/gisops/v1/spatial/user/1 \   -H                          'Content-Type: application/json'                        \   -d                          '{                          "location": {                          "type": "feature",                          "geometry": {                          "type": "Point",                          "coordinates": [                          29.024402,                          40.981047                          ]                          }                          }            }'                      

If you don't get a HTTP 200 and a bulletin like to "Successfully added a location to user nils", in that location's something wrong and you lot amend review all steps again.

Add a new API route - the right way

With the hacky workaround merely about everyone can add or edit a specific user's location. No authentication required. This is ordinarily not what you'd like. The admin, or the user the modify concerns, should be the only ones being allowed to update the location. So, here we nowadays what nosotros'd do for a alive site. Code-wise this is really the easier solution.

First, forget nigh all the changes y'all did to gis_ops-spatial-information-wp-api.php. Instead, create a new file in ./wp-content/plugins/gis_ops_spatial/includes and phone call it spatial-events-listener.php. The new method will exist to add a new field to an existing endpoint: the congenital-in /users. BTW, you'll take to do some of this work in the adjacent department anyways, since and then far, you're only able to update a user'due south location, merely yous can't pull that information yet by whatsoever GET request.

Paste the following code into the new file:

            <?php            /**                          * GIS-OPS spatial listener to add new fields to existing endpoints.                          *                          * @parcel gis_ops_spatial\SpatialEventsListener                          */            course            SpatialEventsListener            {            function            __construct() {            // Add GeoJSON field to Users schema            add_action('rest_api_init',            array(                          $              this            ,            'addGeojsonFieldCallback'));     }            /**                          * Annals hook to add a GeoJSON field to the /users endpoint.                          */            public            office            addGeojsonFieldCallback() {            register_rest_field(            'user',            'location',            array(            'update_callback'            => [                          $              this            ,            'updateGeojsonField'],            'schema'            =>            assortment(            'clarification'            =>            'User location in GeoJSON format.',            'type'            =>            'object',            'context'            =>            array('view',            'edit')                 )             )         );     }            /**                          * Update GeoJSON data from User endpoint                          *                          * @param Object  $geojson                          * @param WP_Post $post                          * @param string   $field_name                          * @return bool|int  Value of GeoJSON field to be added to response                          */            function            updateGeojsonField(              $geojson,                          $post,                          $field_name) {            return            update_user_meta(              $post->id,                          $field_name,                          $geojson);     } }

The addGeojsonFieldCallback function merely calls the WP core register_rest_field function, which ... well, y'all get the idea. It takes equally arguments:

  • object_type: the type of object whose route response you'd like to customize, hither user. Could also exist post, comment or term etc.
  • attribute: the name of the aspect you'd like to annals, here location (you lot should be confident information technology's not conflicting with existing fields for that endpoint)
  • something: an array defining
    • get_callback: the function which will be called when the road gets a Get asking
    • update_callback: the function which volition exist chosen when the route gets a POST/PUT/PATCH HTTP request
    • (optional) schema: set up the expected schema for this data field. Just informational purpose

The API callback function updateGeojsonField couldn't exist any easier: all yous practise is update the meta information entry for your field with the WordPress integrated part update_user_meta. The parameters are added during the callback by WordPress.

Add to plugin skeleton - The right way

Also hither, since the register_rest_field function is executed during the __construction of the new listener class, you lot only take to instantiate it in the plugin base by calculation the post-obit lines to the very bottom in gis_ops.php:

            // Import custom spatial listeners starters            require_once            GISOPS_PLUGIN_PATH            .            '/includes/spatial/spatial-events-listener.php';            // Outset the hook listener                          $spatialEventsListener            =            new            SpatialEventsListener();

Try it out - The right style

That's non and so easy, since POSTing to the users endpoint is restricted to certain privileges, so you can't just curl or apply Postman hands. WordPress comes with cookie authentication out-of-the-box. Which is cumbersome to implement client-side if you're using a frontend framework. And the problem is: that's the but authentication WordPress allows by default.

Thanks to the rich plugin world around WordPress (which clearly tin can be a curse too..), at that place are several alternative ways of authentication to cull from, including social login, basic authentication, LDAP and many more. Still, our favorite which works very well with client frameworks: JWT Hallmark. The documentation is straight-forward, so the setup won't be role of this tutorial.

five Become locations from users

And so far, yous tin can merely add together a location to user entries. And actually that would suffice for our goal of being able to intersect its geometries with a user-provided polygon. But maybe y'all'd similar to just display the location somewhere in the user contour. For that purpose, you'd need to be able to remember the location GeoJSON. If you already added a user following the Try information technology out - hacky workaround section, you can see what happens right now when you try to call back the user yous added a location to: http://localhost:8090/wp-json/wp/v2/users/1. Aye, there's no location field being returned. Permit'due south fix that.

Add a new field for GET requests

If you worked through the "- The right way" sections to update the location for a user, the lawmaking needed for this will wait all too familiar.

If not, create a new file in ./wp-content/plugins/gis_ops_spatial/includes and phone call it spatial-events-listener.php. Paste the following contents (or update the relevant code in case y'all worked through the previous sections):

            <?php            /**                          * GIS-OPS spatial listener to add new fields to existing endpoints.                          *                          * @package gis_ops_spatial\SpatialEventsListener                          */            class            SpatialEventsListener            {            function            __construct() {            // Add GeoJSON field to Users schema            add_action('rest_api_init',            assortment(                          $              this            ,            'addGeojsonFieldCallback'));     }            /**                          * Register hook to add a GeoJSON field to the /users endpoint.                          */            public            function            addGeojsonFieldCallback() {            register_rest_field(            'user',            'location',            array(            'get_callback'            => [                          $              this            ,            'getGeojsonField'],            'schema'            =>            assortment(            'description'            =>            'User location in GeoJSON format.',            'type'            =>            'object',            'context'            =>            array('view',            'edit')                 )             )         );     }            /**                          * Get GeoJSON data from /users endpoint                          *                          * @param Wp_User  $user GeoJSON as object                          * @param string   $field_name                          * @return Object  Value of GeoJSON field to be added to response                          */            function            getGeojsonField(              $user,                          $field_name) {            return            get_user_meta(              $user['id'],                          $field_name,            true);     } }

For a more thorough explanation of the process, refer to Add together a new API route - the right fashion. Hither you just use get_callback and get_user_meta instead of their update_ equivalents.

Try it out

That's already plenty to now also call back the location field when GETting users from WordPress. Effort the same query again: http://localhost:8090/wp-json/wp/v2/users/1.

half-dozen Filter users by bounding box

The final step in this tutorial: implement functionality by which to spatially filter users past polygon. To keep things simple it will only be a bounding box.

Later on this section you will be able to call a new REST API endpoint chosen /user/<id>/intersect with a bbox query parameter and it will return a listing of users whose location intersects with the passed bbox. This could be helpful if y'all (for what reason soever) want to display a leaflet map with the locations of your users in your frontend framework.

Add road for spatial intersection

At this point, you only have to add a REST API road, which executes a office spatially intersecting a supplied bounding box with the users' locations.

The code build on summit of what you've done in Add together a new API route - hacky workaround, then nosotros won't explicate all the nitty-gritty details, simply focus on the new stuff:

            <?php            /**                          * GIS-OPS Spatial Data Wp Api                          *                          * @package gis_ops_spatial\GisOpsSpatialData                          */            class            GisOpsSpatialData            {            individual                          $baseNamespace;            public            function            __construct(              $baseNamespace)     {                          $              this            ->baseNamespace            =                          $baseNamespace;            add_action('rest_api_init',            array(                          $              this            ,            'register_routes'));     }            /**                          * Become plugin namespace.                          * @return string                          */            public            part            get_namespace() {            return                          $              this            ->baseNamespace."/spatial";     }            /**                          * Register boundless api routes for WP API v2.                          */            public            function            register_routes() {            register_rest_route(                          $              this            ->get_namespace(),            'user/(?P<id>\d+)',            array(            'methods'            =>            'Mail',            'callback'            => [              $              this            ,            'update_user']         ));            register_rest_route(                          $              this            ->get_namespace(),            'user/(?P<id>\d+)/intersect',            array(            // <== new stuff            'methods'            =>            'GET',            'callback'            => [              $              this            ,            'get_intersected']         ));     }            /**                          * Updater for /spatial/user POST endpoint. Inserts location into user_meta_data.                          *                          * @param WP_REST_Request $request Full asking data.                          * @render WP_REST_Response|WP_Error Either user information is returned or HTTP 404                          */            function            update_user(              $request) {                          $user            =            get_user_by('id',                          $request['id']);            if            (              $user) {            update_user_meta(              $request['id'],            'location',                          $asking['location']);            return            new            WP_REST_Response("Successfully added a location to user ".              $user->display_name,            200);         }            else            {            render            new            WP_Error('no_user',            'Invalid User ID',            array('condition'            =>            404));         }     }            /**                          * Gets the list of users whose location intersects with the passed bounding box.                          *                          * @param WP_REST_Request $request Full asking information.                          * @return WP_REST_Response List of users                          */            office            get_intersected(              $request) {            // <== new stuff            list(              $min_x,                          $min_y,                          $max_x,                          $max_y) =            explode(',',                          $request->get_param('bbox'));                          $min_x            =            floatval(              $min_x);                          $max_x            =            floatval(              $max_x);                          $min_y            =            floatval(              $min_y);                          $max_y            =            floatval(              $max_y);                          $coordinates            =            array(array(            array(              $min_x,                          $min_y),            array(              $max_x,                          $min_y),            array(              $max_x,                          $max_y),            array(              $min_x,                          $max_y),            array(              $min_x,                          $min_y)         )) ;                          $bounding_box            =            array(            "blazon"            =>            "Feature",            "geometry"            =>            array(            "type"            =>            "Polygon",            "coordinates"            =>                          $coordinates            ),            "properties"            =>            assortment(            "id"            =>            "undefined"            )         );                          $users_matches            =            get_users(array(            'users_per_page'            => -1,            'meta_key'            =>            'location',            'meta_value'            =>                          $bounding_box,            'meta_compare'            =>            'ST_Intersects'            ));                          $controller            =            new            WP_REST_Users_Controller();                          $users_response            = [];            foreach            (                          $users_matches            as                          $user            ) {                          $data            =                          $controller->prepare_item_for_response(              $user,                          $request);                          $users_response[] =                          $controller->prepare_response_for_collection(              $information);         }            render            new            WP_REST_Response(              $users_response,            200);     } }

So, yous'll go about this in a very similar way equally you did when adding the workaround API endpoint to update a user's location: you lot register a new route with register_rest_route, where you add together a callback specifying what should be done, when the route is chosen. In this case, you'll add a Go endpoint which listens on the route user/(?P<id>\d+)/intersect.

The callback expects a parameter called bbox in the request. Since this is a Get request, you'll add the parameter equally a query string parameter to our requests. The bbox parameter is too expected to follow a certain format, i.east. min_lon,min_lat,max_lon,max_lat which is equivalent to the X/Y comma-separated coordinates of a SE and NW betoken spanning a bounding box. The callback and so builds a GeoJSON object from the bounding box (peradventure more than verbose than necessary).

The GeoJSON object is so used in a WordPress meta query using get_users. The meta_compare argument is the operator which is used to compare the meta_value with all values of the meta_key stored in the wp_usermeta table. Ordinarily the meta_compare operator is a standard SQL comparison operator, like =, > or IN. And here is the magic over again: WP GeoMeta automatically detects when the meta_value is a GeoJSON (object or even string) and allows you to utilize MySQL'due south spatial functions to be utilized every bit a meta_compare operator. So, this fiddling slice of code accomplishes the whole spatial functionality: it returns the list of users whose location is intersecting with the provided bounding box from the API call.

At the very terminate, it just constructs the response using born WP_REST_Users_Controller functions. As the class proper name says, that class controls the users Remainder beliefs.

Try it out

Finally, you're at the stride that should feel actually skilful: experiencing that the higher up code actually works.

The new GET endpoint to filter users by bounding box is available on http://localhost:8090/wp-json/gisops/v1/spatial/user/<user_id>/intersect. As explained to a higher place, the lawmaking expects a bbox parameter in a certain format. Gladly, that format happens to be the export format of the well-nigh user-friendly bounding box generator by Klokantech: https://boundingbox.klokantech.com.

In the example above you used our role location at Friedrichstraße 123, 10117 Berlin. Just search for the address in Klokantech's UI, zoom there and apply the bounding box drawer in the upper left to depict a bbox around your address. In the lower left, yous can cull CSV format and copy the CSV-manner bounding box:

Plugin activate

And then use that bounding box value to add to your Become request:

http://localhost:8090/wp-json/gisops/v1/spatial/user/1/intersect?bbox=13.3860517669,52.525561967,13.3885284622,52.5271369451

Hopefully, you also get one single user returned. If there's any other response, you likely did something wrong in the code, the bounding box or the user's location(due south).

To additionally ostend that it'due south working as intended, try to add together a bounding box where you're sure there volition exist no user intersected or add new users with different locations and try different bounding boxes.

7 Concluding plugin

Your final plugin structure should look like this:

├── gisops_wp_spatial │   ├── gis_ops.php │   └── includes │       └── spatial │           ├── gis_ops-spatial-information-wp-api.php │           └── spatial-events-listener.php

If you desire to verify your results, you lot can find the code for the last plugin in our repository.

To go you lot started right abroad, we have included a docker-compose.yml. Go through the Full general Setup if you're having trouble with docker-compose.

To include the full plugin to WordPress, just copy the gisops_wp_spatial folder to ./wp-content/plugins and activate information technology in the WordPress Admin site.

patefropriat.blogspot.com

Source: https://gis-ops.com/wordpress-plugin-tutorial-spatial-capabilities-explained/

0 Response to "Plugin to Upload Arcgis File in Wordpress"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel