How to Fetch and Integrate Multiple Location API Data into Google Maps in WordPress Without Plugins
Rehmatullah Khan

Rehmatullah Khan @rehmatullahbaltikhan

About: I am a Full Stack Developer with over 3 years of experience in the field.

Joined:
Nov 22, 2024

How to Fetch and Integrate Multiple Location API Data into Google Maps in WordPress Without Plugins

Publish Date: Dec 12 '24
0 0

Step-1:
add your google map api in your header.php file:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=Your_API_Key&callback=initMap"></script>

Enter fullscreen mode Exit fullscreen mode

Step-2:
Create Function in Functions.php file for fetch Api adress list and pass to js function:


// Fetch Api Data And Pass data to JavaScript Functions
function enqueue_google_maps_scripts() {

    $url = 'https://example.com/public-api/resources/locations/v2.0';
    $response = wp_remote_get($url, array(
        'headers' => array(
            'Accept' => 'application/json',
            'Authorization' => 'Bearer Your API Token',
        ),
    ));

    if (is_wp_error($response)) {
        error_log('Error fetching data: ' . $response->get_error_message());
        return [];
    }

    $data = wp_remote_retrieve_body($response);
    $locations = json_decode($data, true); // Decode JSON into an array

    // Enqueue Google Maps API
    wp_enqueue_script(
        'google-maps-api',
        'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY',
        [],
        null,
        true
    );

    // Enqueue custom map script
    wp_enqueue_script(
        'custom-google-map',
        get_template_directory_uri() . '/js/custom-google-map.js',
        ['google-maps-api'],
        null,
        true
    );

    // Fetch and pass location data to JavaScript
//     $locations = get_citicharge_locations();

//  echo '<pre>';
//  print_r($locations);
//  echo '</pre>';

    wp_localize_script('custom-google-map', 'citichargeData', [
        'locations' => $locations,
    ]);
}
add_action('wp_enqueue_scripts', 'enqueue_google_maps_scripts');


Enter fullscreen mode Exit fullscreen mode

Step-3:
create js file like /js/custom-google-map.js and add code:


function initMap() {
//  console.log("Initializing map...");
//     console.log("Locations data:", citichargeData.locations);
    var map = new google.maps.Map(document.getElementById("map"), {
        zoom: 5,
        center: { lat: 51.509865, lng: -0.118092 } // Example: Centered on London
    });

    var bounds = new google.maps.LatLngBounds();
    var locations = citichargeData.locations;
//     var locations = [
//         {
//             geoposition: { latitude: 42.6710963, longitude: 23.3520653 },
//             name: [{ translation: "Ampeco Office" }],
//             address: [{ translation: "Sofia, Bulgaria" }]
//         },
//         {
//             geoposition: { latitude: 51.5194133, longitude: -0.1269566 },
//             name: [{ translation: "British Museum" }],
//             address: [{ translation: "London, UK" }]
//         }
//         // Add other locations
//     ];
    locations.data.forEach(function (location) {
//      console.log("Loop Data",location);
        var position = {
            lat: location.geoposition.latitude,
            lng: location.geoposition.longitude
        };
//      console.log("position",position);

        var marker = new google.maps.Marker({
            position: position,
            map: map,
            title: location.name[0].translation
        });

        var infoWindow = new google.maps.InfoWindow({
            content: ` <h4>${location.name[0].translation}</h4>
                        <p>${location.address[0].translation}</p>
                        <button onclick="viewOnGoogleMaps(${location.geoposition.latitude}, ${location.geoposition.longitude})">View on Google Maps</button>`
        });

        marker.addListener("click", function () {
            infoWindow.open(map, marker);
        });

        bounds.extend(position);
    });

    map.fitBounds(bounds);
}

function viewOnGoogleMaps(lat, lng) {
    var googleMapsUrl = `https://www.google.com/maps?q=${lat},${lng}`;
    window.open(googleMapsUrl, '_blank'); // Open Google Maps in a new tab
}


Enter fullscreen mode Exit fullscreen mode

Step-4:
create shortcod for display Google Map:

function display_google_map_shortcode() {
    return '<div id="map" style="width: 100%; height: 500px;"></div>';
}
add_shortcode('google_map', 'display_google_map_shortcode');

Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment