Malaysia Taps Precision Spraying Tech To Outsmart Devastating Bagworms
Terra Drone Agri takes to the skies to tame the bagworm menace in Malaysian oil palm plantations. …
23. December 2024
Unlocking the Power of Multiple Location API Data on Google Maps in WordPress
To take your WordPress site to the next level, seamlessly integrate multiple location API data into Google Maps without relying on plugins. This article will guide you through the process with expert insights from web development and geolocation.
Step 1: Embed Google Maps API in Your Header
Add your Google Maps API key to header.php
to enable the Google Maps script on your website. Replace YOUR_API_KEY
with your actual API key.
1<script async defer src="https://maps.googleapis.com/maps/api/js?key=Your_API_Key&callback=initMap"></script>
Step 2: Fetch and Pass Location Data
In functions.php
, create a function called enqueue_google_maps_scripts()
to fetch API address data from your public API endpoint. This script will also enqueue the necessary Google Maps API scripts.
1function enqueue_google_maps_scripts() {
2$url = 'https://example.com/public-api/resources/locations/v2.0';
3$response = wp_remote_get($url, array(
4'headers' => array(
5'Accept' => 'application/json',
6'Authorization' => 'Bearer Your_API_TOKEN',
7),
8));
9
10if (is_wp_error($response)) {
11error_log('Error fetching data: ' . $response->get_error_message());
12return [];
13}
14
15$data = wp_remote_retrieve_body($response);
16$locations = json_decode($data, true);
17
18// Enqueue Google Maps API
19wp_enqueue_script('google-maps-api', 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY', [], null, true);
20
21// Fetch and pass location data to JavaScript
22wp_localize_script('custom-google-map', 'citichargeData', ['locations' => $locations]);
23}
24
25add_action('wp_enqueue_scripts', 'enqueue_google_maps_scripts');
Step 3: Create a Custom Google Map Script
In the js
directory, create a new file called custom-google-map.js
. This script will initialize the Google Maps map and add markers for each location.
1function initMap() {
2// console.log("Initializing map...");
3// console.log("Locations data:", citichargeData.locations);
4
5var map = new google.maps.Map(document.getElementById("map"), {
6zoom: 5,
7center: { lat: 51.509865, lng: -0.118092 },
8});
9
10var bounds = new google.maps.LatLngBounds();
11
12locations.data.forEach(function (location) {
13// console.log("Loop Data", location);
14var position = {
15lat: location.geoposition.latitude,
16lng: location.geoposition.longitude,
17};
18
19var marker = new google.maps.Marker({
20position: position,
21map: map,
22title: location.name[0].translation,
23});
24
25var infoWindow = new google.maps.InfoWindow({
26content: `
27<h4>${location.name[0].translation}</h4>
28<p>${location.address[0].translation}</p>
29<button onclick="viewOnGoogleMaps(${location.geoposition.latitude}, ${location.geoposition.longitude})">View on Google Maps</button>
30`,
31});
32
33marker.addListener("click", function () {
34infoWindow.open(map, marker);
35});
36
37bounds.extend(position);
38});
39
40map.fitBounds(bounds);
41}
42
43function viewOnGoogleMaps(lat, lng) {
44var googleMapsUrl = `https://www.google.com/maps?q=${lat},${lng}`;
45window.open(googleMapsUrl, '_blank');
46}
Step 4: Display Google Map To display the Google Map on your WordPress site, add a shortcode in your content editor. Use the following code to create a basic map:
1[google-map lat="51.509865" lng="-0.118092" zoom="5"]
Replace 51.509865
and -0.118092
with your desired location coordinates.
With these steps, you’ve successfully integrated multiple location API data into Google Maps on your WordPress site without relying on plugins. The power of geolocation is now at your fingertips!
To improve performance, consider caching map tiles using a plugin. If dealing with large numbers of locations, optimize API requests by implementing pagination or lazy loading techniques. For more advanced customization options, explore the official Google Maps JavaScript API documentation and tutorials.