Google Maps Advanced Distance & Pricing Engine
A production-ready WordPress plugin that calculates real driving distance via the Google Maps Distance Matrix API and returns a dynamic price estimate — built for pharmacy delivery, taxi fare, and food delivery use cases.
by Fardeen Ahmad (Weblix Studios) · github.com/iammfardeen/gm-advanced-distance-pricing-engine · website
Install
No release zip yet. The repository archive installs, but the folder name will carry the branch suffix and updates will not flow:
wp plugin install https://github.com/iammfardeen/gm-advanced-distance-pricing-engine/archive/refs/heads/main.zipReadme
Google Maps Advanced Distance & Pricing Engine
A production-ready WordPress plugin that calculates real driving distance via the Google Maps Distance Matrix API and returns a dynamic price estimate — built for pharmacy delivery, taxi fare, and food delivery use cases.
Author: Fardeen Ahmad — Weblix Studios
Version: 1.0.0
License: GPLv2 or later
Requires WordPress: 5.8+
Requires PHP: 7.4+
Table of Contents
- Overview
- Features
- How It Works
- Installation
- Configuration
- Shortcode Usage
- Use Case Examples
- Caching Behaviour
- Security Model
- Google Cloud Setup
- Frequently Asked Questions
- Changelog
- License
Overview
Most distance-based pricing plugins rely on straight-line (as-the-crow-flies) math, which gives inaccurate results the moment roads curve, rivers intervene, or a one-way street system exists. This plugin queries the Google Maps Distance Matrix API for the actual road-network driving distance between any two addresses — then applies a configurable per-kilometre rate to produce a final price estimate.
The result is rendered in a clean card UI that displays the resolved addresses, driving distance, estimated travel duration, and computed cost — all from a single shortcode.
Features
- Real driving distance — uses the Google Maps Distance Matrix API, not haversine math
- Driving duration — shows estimated travel time pulled directly from the API response
- Dynamic pricing formula —
Distance (km) × Rate Multiplier = Final Cost - Admin settings panel — configure API key, currency symbol, and per-km rate via Settings → Distance Pricing
- 12-hour transient cache — successful API responses are cached using the WordPress Transients API, preventing duplicate calls for the same address pair
- Object-oriented, single-file architecture — no extra files or directories required
- Fully sanitized inputs and escaped outputs — every value is validated before storage and escaped before rendering
- Translation-ready — text domain
gm-distance-pricingwith full__()/esc_html_e()coverage - Accessible card output — semantic HTML with
role,aria-label, and reduced-motion-safe CSS
How It Works
[calculate_shipping origin="..." destination="..."]
│
▼
sanitize_text_field() on both addresses
│
▼
Build MD5 cache key from normalised address pair
│
┌────┴────┐
Cache HIT Cache MISS
│ │
│ wp_remote_get()
│ → Google Maps Distance Matrix API
│ ← JSON response
│ → Validate HTTP + API status
│ → set_transient() for 12 hours
└────┬────┘
│
distance_km × multiplier = final_cost
│
▼
Render HTML card with esc_html() on all output
Installation
Option A — Manual Upload
- Download or clone this repository.
- Place the file
gm-distance-pricing-engine.phpinside a folder namedgm-distance-pricing:/wp-content/plugins/gm-distance-pricing/gm-distance-pricing-engine.php - Log in to your WordPress admin and navigate to Plugins → Installed Plugins.
- Find Google Maps Advanced Distance & Pricing Engine and click Activate.
Option B — Upload via Admin
- Zip the
gm-distance-pricingfolder. - Go to Plugins → Add New → Upload Plugin.
- Upload the zip and click Install Now, then Activate.
Configuration
After activation, go to Settings → Distance Pricing in your WordPress admin.
| Setting | Description | Default |
|---|---|---|
| Google Maps API Key | Your key from Google Cloud Console. Must have Distance Matrix API enabled. | (empty) |
| Currency Symbol | Shown before the calculated price. Accepts up to 5 characters. | $ |
| Rate Multiplier (per km) | Cost per kilometre. Final price = distance × this value. | 1.5 |
Click Save Settings when done.
Shortcode Usage
Place this shortcode in any post, page, or widget:
[calculate_shipping origin="YOUR ORIGIN" destination="YOUR DESTINATION"]
Both origin and destination accept any address string that Google Maps can resolve — street addresses, city names, landmarks, or pin codes.
Parameters
| Parameter | Required | Description |
|---|---|---|
origin |
Yes | Starting address (e.g., "Connaught Place, New Delhi") |
destination |
Yes | Ending address (e.g., "Sector 18, Noida") |
Output Card
The shortcode renders a card showing:
- ✅ Resolved origin address (as confirmed by Google)
- ✅ Resolved destination address
- 🛣️ Driving distance (e.g.,
18.3 km) - ⏱️ Estimated driving duration (e.g.,
34 mins) - 💰 Computed price (e.g.,
₹27.45) - Formula breakdown in the footer
- Cache indicator when result is served from transient
Use Case Examples
Pharmacy / Medical Delivery
[calculate_shipping origin="Apollo Pharmacy, Lajpat Nagar, Delhi" destination="Saket, New Delhi"]
Set your multiplier to the per-km delivery charge (e.g., 8 for ₹8/km with currency ₹).
Taxi / Cab Fare Estimate
[calculate_shipping origin="Indira Gandhi International Airport, Delhi" destination="Karol Bagh, New Delhi"]
Set your multiplier to match your base fare per kilometre (e.g., 12 for ₹12/km).
Restaurant Food Delivery
[calculate_shipping origin="Zahra Restaurant, Jamia Nagar, New Delhi" destination="Okhla Phase 1, Delhi"]
Set a lower multiplier (e.g., 5) combined with a flat base charge baked into your checkout logic.
Caching Behaviour
Each unique origin + destination pair caches its API response for 12 hours using set_transient().
- The cache key is:
gmdpe_dist_+md5( lowercase(origin) . '|' . lowercase(destination) ) - Address normalisation (lowercase + trim) ensures
"New Delhi"and"new delhi"share one cache entry - Errors are never cached — a failed API call will retry on the next page load
- Cache is automatically cleared when WordPress flushes transients (e.g., on cron jobs or object cache flush)
- The output card displays an ⚡ indicator when a result is served from cache
To manually clear a cached route, you can use a plugin like Transients Manager and delete keys prefixed with gmdpe_dist_.
Security Model
| Layer | Implementation |
|---|---|
| Direct file access | ABSPATH guard at the top of the file — exits immediately if WordPress is not loaded |
| Admin capability | Settings page requires manage_options capability; enforced at both menu registration and page render |
| Form security | WordPress Settings API handles nonce verification and options.php POST automatically |
| Input sanitization | sanitize_text_field() on API key and currency; floatval() + floor guard on multiplier |
| API URL building | add_query_arg() with rawurlencode() — no raw user input concatenated into URLs |
| Output escaping | Every dynamic value passed through esc_html() or esc_attr() before HTML output |
| Unknown shortcode attributes | shortcode_atts() strips all attributes not declared in the defaults array |
| SSL enforcement | wp_remote_get() called with 'sslverify' => true |
Google Cloud Setup
- Go to Google Cloud Console.
- Create a new project (or select an existing one).
- Navigate to APIs & Services → Library.
- Search for Distance Matrix API and click Enable.
- Go to APIs & Services → Credentials → Create Credentials → API Key.
- Copy the generated key and paste it into Settings → Distance Pricing → Google Maps API Key.
Recommended: Restrict your API key in the Google Cloud Console to only the Distance Matrix API and to your server's IP address to prevent unauthorized usage.
Frequently Asked Questions
Q: Why is my price showing an error about the API key?
Go to Settings → Distance Pricing and verify your API key is entered correctly. Also confirm the Distance Matrix API is enabled in your Google Cloud project under APIs & Services.
Q: Can I use city names instead of full street addresses?
Yes. Google's geocoding resolves city names, landmarks, postal codes, and full addresses. For best accuracy, include the city and country (e.g., "Saket, New Delhi, India").
Q: Does this use straight-line distance?
No. The plugin exclusively uses the Google Maps Distance Matrix API which returns actual road-network driving distance, including turns, one-way streets, and road closures at the time of the request.
Q: Can I display multiple shortcodes on the same page?
Yes. Each shortcode instance is independent. They may share cached results if the address pairs match.
Q: How do I add a flat base fee on top of the per-km rate?
Currently the formula is distance × multiplier. A flat fee can be added by setting the multiplier higher to approximate it, or by extending the plugin with a base_fee shortcode attribute in a child plugin or custom code snippet.
Q: Is this plugin GDPR-compliant?
The plugin sends origin and destination address strings to Google's Distance Matrix API for distance lookup. These are user-supplied addresses, not personal data. Review Google's API Terms of Service for your region's compliance requirements.
Changelog
1.0.0 — Initial Release
- Google Maps Distance Matrix API integration via
wp_remote_get() - 12-hour transient caching with MD5-keyed address pairs
- WordPress Settings API admin panel with sanitized option storage
[calculate_shipping]shortcode with fully escaped HTML card output- GPLv2+ open-source license
- Translation-ready with text domain
gm-distance-pricing
License
Google Maps Advanced Distance & Pricing Engine is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but without any warranty — without even the implied warranty of merchantability or fitness for a particular purpose. See the GNU General Public License for more details.
Built with ❤️ by Fardeen Ahmad — Weblix Studios, New Delhi.