Neil Matthews

Blog

  • Integrating JavaScript Geolocation Data into PHP: A Comprehensive Guide

    Integrating JavaScript Geolocation Data into PHP: A Comprehensive Guide

    In modern web development, the seamless integration of client-side JavaScript with server-side PHP opens up a plethora of possibilities for creating dynamic and interactive web applications. One common scenario involves capturing geolocation data using JavaScript and passing it to PHP for further processing or storage. In this blog post, we’ll explore various methods and techniques for achieving this integration, allowing developers to harness the power of both languages to enhance their web applications.

    Understanding the Workflow

    Before diving into the implementation details, let’s outline the general workflow of passing JavaScript geolocation data into a PHP variable:

    1. Capture Geolocation: Use JavaScript to obtain the user’s geolocation data, such as latitude and longitude coordinates.
    2. Send Data to Server: Transfer the geolocation data from JavaScript to PHP, typically via an HTTP request.
    3. Process Data in PHP: Receive the geolocation data on the server-side using PHP and perform any necessary operations, such as storing it in a database or utilizing it in server-side logic.

    Now, let’s explore each step in more detail.

    Step 1: Capture Geolocation with JavaScript

    JavaScript provides the Geolocation API, which allows web applications to access the user’s geographical location. Here’s a basic example demonstrating how to retrieve the user’s coordinates using JavaScript:

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            const latitude = position.coords.latitude;
            const longitude = position.coords.longitude;
    
            // Call function to send data to server
            sendDataToServer(latitude, longitude);
        });
    } else {
        console.error("Geolocation is not supported by this browser.");
    }

    In this code snippet, we use getCurrentPosition() to obtain the user’s current position. Once we have the latitude and longitude coordinates, we call a function (sendDataToServer()) to send this data to the server.

    Step 2: Send Data to Server

    To send the geolocation data from JavaScript to PHP, we typically use an asynchronous HTTP request, such as AJAX. Here’s how you can send the data using jQuery’s AJAX method:

    function sendDataToServer(latitude, longitude) {
        $.ajax({
            type: "POST",
            url: "process.php",
            data: { latitude: latitude, longitude: longitude },
            success: function(response) {
                console.log("Data sent successfully: " + response);
            },
            error: function(xhr, status, error) {
                console.error("Error sending data to server: " + error);
            }
        });
    }

    In this example, we use a POST request to send the latitude and longitude coordinates to a PHP script called process.php. Adjust the URL (url: "process.php") to match the path to your PHP script.

    Step 3: Process Data in PHP

    On the server-side, you can access the geolocation data sent from JavaScript using PHP’s $_POST superglobal. Here’s how you can retrieve the latitude and longitude coordinates in your PHP script (process.php):

    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $latitude = $_POST["latitude"];
        $longitude = $_POST["longitude"];
    
        // Process the geolocation data (e.g., store in database)
        // Example: Insert data into a MySQL database
        // $mysqli = new mysqli("localhost", "username", "password", "database");
        // $mysqli->query("INSERT INTO locations (latitude, longitude) VALUES ('$latitude', '$longitude')");
    
        echo "Data received successfully: Latitude - $latitude, Longitude - $longitude";
    } else {
        echo "Invalid request method.";
    }
    ?>

    In this PHP script, we retrieve the latitude and longitude coordinates from the $_POST superglobal. You can then perform any necessary operations with the geolocation data, such as storing it in a database or using it in server-side logic.

    Conclusion

    By following the outlined steps, developers can seamlessly pass JavaScript geolocation data into PHP variables, enabling the creation of dynamic and location-aware web applications. Whether it’s for location-based services, personalized content delivery, or data analysis, integrating client-side JavaScript with server-side PHP empowers developers to leverage the strengths of both languages and create compelling web experiences. With this knowledge in hand, you’re well-equipped to incorporate geolocation functionality into your PHP-powered web applications and unlock new possibilities for engaging user experiences.

    Photo by Jannes Glas on Unsplash

  • The Pitfalls of Mobile Data IP Address Lookup for Geolocation: A Cautionary Tale

    The Pitfalls of Mobile Data IP Address Lookup for Geolocation: A Cautionary Tale

    In the age of smartphones and constant connectivity, geolocation plays a pivotal role in enhancing user experiences across various applications and services. Whether it’s for navigation, location-based recommendations, or targeted advertising, accurate geolocation data is invaluable. However, relying solely on IP address lookup for geolocation, especially when users are on mobile data networks rather than Wi-Fi, can lead to significant inaccuracies and shortcomings. In this blog post, we delve into the reasons why IP address lookup on mobile phones using mobile data is not optimal for geolocation due to the nature of IP addresses assigned by mobile service providers.

    Understanding Geolocation and IP Address Lookup

    Geolocation, in its simplest form, involves determining the geographic location of a device, such as a smartphone or computer. One common method used for geolocation is IP address lookup, where the IP address of the device is used to infer its approximate geographical location.

    IP addresses, unique identifiers assigned to devices connected to the internet, are typically associated with specific geographic regions. When a device connects to the internet, its IP address is assigned based on its network connection, whether it’s through Wi-Fi or mobile data.

    Challenges with Mobile Data IP Address Lookup

    While IP address lookup works reasonably well for geolocation on desktop computers and devices connected to Wi-Fi networks, it presents several challenges when it comes to mobile phones using mobile data connections. Here’s why:

    1. Dynamic IP Address Assignment: Mobile service providers often use dynamic IP address assignment for mobile data connections. This means that a user’s IP address can change frequently as they move between different cellular towers or as network conditions fluctuate. Consequently, relying solely on the IP address for geolocation can lead to inaccuracies, as the assigned IP address may not accurately reflect the user’s actual location.
    2. Carrier-Level IP Address Allocation: Mobile service providers typically allocate IP addresses from a pool of addresses owned by the carrier. These IP addresses may not necessarily correspond to the user’s physical location. For example, a user in New York City might be assigned an IP address that belongs to the carrier’s network infrastructure located in a different state. As a result, geolocating based on the IP address alone can lead to incorrect assumptions about the user’s whereabouts.
    3. Proxy Servers and VPNs: Many mobile users employ proxy servers or virtual private networks (VPNs) to enhance privacy and security while browsing the internet. These tools route internet traffic through servers located in different geographic locations, masking the true IP address of the device. Consequently, geolocating based on the IP address may point to the location of the proxy server or VPN endpoint rather than the user’s actual location.

    Alternative Geolocation Techniques for Mobile Devices

    Given the limitations of IP address lookup for geolocation on mobile devices using mobile data, developers should explore alternative techniques for obtaining accurate location data. These may include:

    • GPS: Leveraging the device’s built-in GPS capabilities provides highly accurate location data, especially outdoors.
    • Cellular Tower Triangulation: Utilizing information from nearby cellular towers can approximate the device’s location, albeit with lower accuracy compared to GPS.
    • Wi-Fi Access Point Trilateration: When Wi-Fi is available, triangulating the device’s position based on nearby Wi-Fi access points can provide relatively accurate location data.

    Conclusion

    While IP address lookup serves as a convenient method for geolocation on desktops and Wi-Fi-connected devices, its effectiveness diminishes when applied to mobile phones using mobile data connections. Dynamic IP address assignment, carrier-level allocation, and the prevalence of proxy servers and VPNs contribute to inaccuracies and inconsistencies in geolocation data. Developers and service providers must recognize these limitations and explore alternative techniques for obtaining accurate location data on mobile devices. By employing a combination of GPS, cellular tower triangulation, and Wi-Fi access point trilateration, developers can deliver enhanced location-based experiences that cater to the dynamic nature of mobile usage.

    Do you have a gelocation project you need help with, please reach out to me.

    Photo by Anne Nygård on Unsplash

  • Redirecting Using JavaScript Geolocation

    Redirecting Using JavaScript Geolocation

    Introduction

    In WordPress, redirecting users to specific pages based on their geographical location can enhance user experience and provide targeted content. Leveraging JavaScript’s Geolocation API allows developers to obtain user location data and dynamically redirect them to relevant pages within a WordPress website. This technical document outlines the steps to implement geolocation-based redirection using JavaScript in a WordPress environment.

    Prerequisites

    1. Basic understanding of JavaScript programming.
    2. Access to the WordPress website’s theme files or ability to edit WordPress templates.
    3. Understanding of WordPress hooks and actions.

    Steps to Implement Geolocation-based Redirection

    Step 1: Enqueue JavaScript File

    First, enqueue a custom JavaScript file in your WordPress theme to handle geolocation and redirection logic. You can add the following code snippet to your theme’s functions.php file or create a custom plugin:

    function enqueue_custom_script() {
        wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array(), '1.0', true );
    }
    add_action( 'wp_enqueue_scripts', 'enqueue_custom_script' );

    Ensure that the path to your custom JavaScript file is correct (/js/custom-script.js in this example).

    Step 2: Write JavaScript Logic

    In your custom JavaScript file (custom-script.js), write the logic to obtain the user’s geolocation and redirect them to the appropriate page. Below is a basic example:

    document.addEventListener('DOMContentLoaded', function() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                // Retrieve latitude and longitude
                const latitude = position.coords.latitude;
                const longitude = position.coords.longitude;
    
                // Logic to determine redirection based on coordinates
                if (/* Your condition for redirection based on coordinates */) {
                    window.location.href = 'https://example.com/page-to-redirect';
                }
            });
        }
    });

    Replace 'https://example.com/page-to-redirect' with the URL of the page you want to redirect users to based on their location. Additionally, implement your own conditions for determining the redirection based on latitude and longitude.

    Step 3: Testing and Refinement

    Test the implementation thoroughly on various devices and locations to ensure proper functionality. Refine the redirection logic as needed to provide accurate and relevant redirections based on user location.

    Considerations

    1. Fallback Mechanism: Provide a fallback mechanism for users whose browsers do not support geolocation or who have denied location access. Consider displaying a message or offering alternative navigation options.
    2. Privacy and Consent: Respect user privacy and obtain explicit consent before accessing their location data. Clearly communicate how their data will be used and provide options for opting out of location-based redirection.
    3. Performance: Optimize the implementation for performance, considering factors such as asynchronous loading of scripts and minimizing unnecessary redirects.

    Conclusion

    Implementing geolocation-based redirection in WordPress using JavaScript enhances user experience by delivering targeted content based on their geographical location. By following the outlined steps and considerations, developers can create dynamic and personalized experiences that cater to the diverse needs of users across different regions. This approach not only improves engagement but also adds value to the overall usability of WordPress websites.

    If you need help with this type of coding please get in touch.

    Photo by Sylwia Bartyzel on Unsplash

  • JavaScript for Geolocation: Enhancing User Experience

    JavaScript for Geolocation: Enhancing User Experience

    In today’s interconnected digital landscape, harnessing the power of geolocation has become integral to providing personalized and location-based services to users. Whether it’s delivering targeted content, facilitating navigation, or offering location-aware recommendations, geolocation adds a layer of contextual relevance that enhances user experience. JavaScript, being the backbone of web development, offers robust tools and APIs for accessing geolocation data, empowering developers to create dynamic and location-aware web applications.

    Understanding Geolocation in JavaScript

    JavaScript provides the Geolocation API, a powerful toolset that enables web applications to access the user’s geographical location. This API allows developers to retrieve the device’s latitude and longitude coordinates, along with other relevant information such as altitude, accuracy, and heading.

    Obtaining Geolocation Data

    To fetch the user’s current location using JavaScript, you can utilize the navigator.geolocation object. Here’s a basic example demonstrating how to retrieve the user’s coordinates:

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        console.log("Geolocation is not supported by this browser.");
    }
    
    function showPosition(position) {
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;
    
        console.log("Latitude: " + latitude + ", Longitude: " + longitude);
    }

    In this code snippet:

    • We first check if the browser supports geolocation.
    • If supported, we call getCurrentPosition() method, which triggers a request to obtain the current position of the device.
    • Upon successful retrieval, the showPosition() function is invoked, passing a Position object containing the coordinates.

    Handling Errors and Options

    It’s essential to handle errors gracefully and provide fallback mechanisms in case geolocation retrieval fails or is denied by the user. Additionally, you can specify options such as maximum age, timeout, and desired accuracy level when fetching geolocation data.

    const options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
    };
    
    function error(err) {
        console.warn(`ERROR(${err.code}): ${err.message}`);
    }
    
    navigator.geolocation.getCurrentPosition(showPosition, error, options);

    Integrating Geolocation into Applications

    Once you’ve obtained the user’s geolocation data, the possibilities are endless. You can leverage this information to customize user experiences, tailor content based on location, offer localized services, or enhance navigation functionalities.

    For example, you could display nearby points of interest, provide weather updates specific to the user’s location, or optimize route planning in a mapping application.

    Privacy and Security Considerations

    While geolocation offers tremendous utility, it’s crucial to prioritize user privacy and security. Always seek explicit consent from users before accessing their location data. Provide clear explanations of how and why their data will be used, and offer granular controls for managing location permissions.

    Conclusion

    Incorporating geolocation into web applications using JavaScript opens up a world of possibilities for delivering personalized and location-aware experiences to users. By harnessing the Geolocation API and implementing best practices for privacy and security, developers can create immersive and contextually relevant applications that elevate the user experience to new heights. Whether it’s for e-commerce, social networking, travel, or any other domain, geolocation empowers developers to build dynamic and engaging web experiences that resonate with users on a personal level.

    If you need help coding up a geolocation solution for your site, please get in touch.

    Photo by henry perks on Unsplash

  • Why I’m Using Sub-Domains To Test My Offers

    Why I’m Using Sub-Domains To Test My Offers

    I’ve started to create mini sites on subdomains to test my offers. I this post I’ll explain why.

    What Do I Mean By An Offer

    What I mean by an offer is something I am selling, in my case it’s mostly a service. I’m testing targeted services at the moment which are productised WordPress offering of various descriptions.

    Often I’m not sure if people need these services so I’m testing that offer.

    What Is A Sub-Domain Mini Site?

    It’s a very small website marketing a single offer on a subdomain e.g. offer.neilmatthews.com. It’s separate from your main site and acts as a website in it’s own right.

    It sets out my offer in detail and has a single call to action to direct people to interact with me in some way (see controlling the CTA below).

    A Targeted Message

    It allows me to create a targeted message about the service I’m offering without all the baggage the rest of my site brings. If I’m talking about an AI service such as my customer support solution at wpaics.neilmatthews.com I don’t want to be talking about hiring me for a generic WordPress project or joining my ongoing maintenance plan. That additional content just causes confusion, and a confused client never buys.

    Showing those other offers just causes confusion, so using a cut down mini-site with 2 or 3 pages allows me to give all the information needed.

    Plus I can create highly targeted SEO content for a single set of keywords and drive traffic to my offers.

    Monitor Traffic

    Because I’m sending traffic to the mini site I can gauge how well it’s working by analysing the traffic to that mini site and not have the analytics diluted by the other traffic to my main site.

    Some Offers Never Stick

    Some of the offers I create neve take off, they never stick, creating them in isolation means I don’t need to make big changes to my main site and my main offer of WordPress development services.

    If I find an offer does not resonate I can very easily take it down.

    If it does work, I can bring it to my main site or leave it where it is, no need to disturb my main offer if I don’t need to.

    Closing An Offer

    When I no longer want to make an offer it’s very simple to close it. All I need to do is take down the sub-domain and all references to the offer are gone.

    I recently has someone try to buy a hack recovery course I created in 2017 and that I no longer offer. I had to refund their payment and search around my site for the landing page that sold the course to take that down, it’s easier to close an offer if it is self contained.

    Controlling The CTA (Call To Action)

    Some of my offers are about taking a trial, some of my offers are lead magnets, some are to request a quote and some are to book a call.

    Having mini-sites for different offers means I can direct a potential client to the correct call to action rather than a generic contact me page.

    Different Sites For Different Audience Types

    If I have two different type of audience, sending them to the same site will cause confusion.

    By segmenting audience types and sending them to the correct mini sites mean better markeing.

    For example, I offer an ongoing support plan for WordPress sites, I also offer a white label version of that plan I sell to agencies, WordPress freelancers and designers. Sending both groups to the same marketing will not work, I’ll send people with a single site to my maintenance page and the others to my white label support mini site maintenanceplan.neilmatthew.com.

    Some Of My Offers & Planned Offers.

    Here are some of the offers I’ve spun out to their own sub-domain mini-sites.

    I’m thinking about spinning out a new type of asynchronous consulting offer and a WooCommerce optimization service but that’s for the future.

    Why Not Use A Landing Page

    A landing page is exactly that, a single page if I have a mini site solely focused on an offer I can create custom about pages, custom FAQs and custom call to actions.

    It’s like a landing page on steroids.

    Traffic To The Offers

    Another benefit of mini sites is controlling which traffic I send to which offer.

    I could send targeted traffic to a landing page but I can send targeted traffic to a mini site and get the same results and provide more information.

    Wrap Up – Why I’m Using Sub-Domains To Test My Offers

    As you can see creating mini sites is all about controlling confusion, give the right message to the right person to avoid confusion.

    Say it with me kids “A confused client never buys!”.

    If you need help building mini sites for your offers get in touch.

    Photo by Marc-Antoine Déry on Unsplash

  • Enhancing Google Map Markers: Adding Post Title and Excerpt with ACF Google Map Field

    Enhancing Google Map Markers: Adding Post Title and Excerpt with ACF Google Map Field

    Introduction:Enhancing Google Map Markers

    In this blog post, we’ll explore a practical scenario where we not only display Google Map markers using the ACF Google Map field but also enrich them with additional information such as post title and excerpt. By combining the power of ACF and Google Maps API, we can create a more informative and engaging mapping experience for users.

    Getting Started:

    Ensure you have the ACF plugin installed and activated on your WordPress site, and create a custom field group with a Google Map field. Additionally, have the Google Maps API key ready, as we’ll be using it to display the map.

    1. Modify ACF Field Group: Open your ACF field group and ensure you have the necessary fields, including the Google Map field, post title, and post excerpt.
       add_action('acf/init', 'my_acf_init');
       function my_acf_init() {
          acf_add_local_field_group(array(
             // Field group settings...
             'fields' => array(
                array(
                   'key' => 'field_location',
                   'label' => 'Location',
                   'name' => 'location',
                   'type' => 'google_map',
                   // Additional settings...
                ),
                // Other fields...
             ),
          ));
       }

    Displaying Google Map with Markers:

    Now, let’s create a template file or modify an existing one to output the Google Map with markers, including post title and excerpt.

    1. Outputting Google Map with Markers:
       <?php
       // Get the current post ID
       $post_id = get_the_ID();
    
       // Retrieve location data from the ACF Google Map field
       $location = get_field('location', $post_id);
    
       // Output Google Map with markers
       ?>
       <div id="map-container">
          <div id="map" data-lat="<?php echo esc_attr($location['lat']); ?>" data-lng="<?php echo esc_attr($location['lng']); ?>"></div>
       </div>

    Don’t forget to include the Google Maps API script as mentioned in the previous blog post.

    1. Enhancing Markers with Post Title and Excerpt:
       <script>
          function initMap() {
             var mapElement = document.getElementById('map');
             var lat = parseFloat(mapElement.getAttribute('data-lat'));
             var lng = parseFloat(mapElement.getAttribute('data-lng'));
    
             var map = new google.maps.Map(mapElement, {
                center: { lat: lat, lng: lng },
                zoom: 15
             });
    
             var marker = new google.maps.Marker({
                position: { lat: lat, lng: lng },
                map: map,
                title: '<?php echo esc_js(get_the_title($post_id)); ?>', // Post title as marker title
             });
    
             // Info window with post excerpt
             var infowindow = new google.maps.InfoWindow({
                content: '<h3><?php echo esc_js(get_the_title($post_id)); ?></h3><p><?php echo esc_js(get_the_excerpt($post_id)); ?></p>'
             });
    
             // Open info window on marker click
             marker.addListener('click', function() {
                infowindow.open(map, marker);
             });
          }
       </script>

    Conclusion:Enhancing Google Map Markers

    By following these steps and incorporating the provided code snippets, you can elevate your Google Map markers by adding post title and excerpt information. This not only enhances the visual representation of locations but also provides users with valuable context about each marker. Customize the code further to suit your specific needs and create a truly engaging mapping experience on your WordPress site.

    If you need help integrating Google maps with your site give me a shout.

    Photo by Andrew Neel on Unsplash

  • Elevating Your Location Data: A Guide to Storing Latitude and Longitude with ACF Google Map Field

    Elevating Your Location Data: A Guide to Storing Latitude and Longitude with ACF Google Map Field

    Introduction: Latitude and Longitude with ACF Google Map

    In this technical blog post, we’ll not only explore the importance of storing latitude and longitude as separate fields alongside ACF Google Map data but also provide you with the code snippets to seamlessly save this information. Join us on this journey to enhance your location-based queries and improve the efficiency of your WordPress site.

    Storing Latitude and Longitude Data:

    Before we dive into the code, let’s make sure we have separate latitude and longitude fields within the ACF field group.

    1. Modify ACF Field Group: Open your ACF field group and ensure you have added two additional fields named latitude and longitude.
       add_action('acf/init', 'my_acf_init');
       function my_acf_init() {
          acf_add_local_field_group(array(
             // Field group settings...
             'fields' => array(
                array(
                   'key' => 'field_latitude',
                   'label' => 'Latitude',
                   'name' => 'latitude',
                   'type' => 'number',
                   // Additional settings...
                ),
                array(
                   'key' => 'field_longitude',
                   'label' => 'Longitude',
                   'name' => 'longitude',
                   'type' => 'number',
                   // Additional settings...
                ),
                array(
                   'key' => 'field_location',
                   'label' => 'Location',
                   'name' => 'location',
                   'type' => 'google_map',
                   // Additional settings...
                ),
                // Other fields...
             ),
          ));
       }

    Saving Latitude and Longitude Data:

    Now, let’s add the necessary code to automatically save the latitude and longitude values when a user selects a location on the Google Map field.

    1. Hook into ACF Save Post Action:
       add_action('acf/save_post', 'save_latitude_longitude', 20);
    
       function save_latitude_longitude($post_id) {
          // Ensure this is not an autosave or a post revision.
          if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
          if (wp_is_post_revision($post_id)) return;
    
          // Check if the post type is the one associated with your ACF field group.
          if (get_post_type($post_id) === 'your_custom_post_type') {
             // Get the location data from the Google Map field.
             $location = get_field('location', $post_id);
    
             // Save latitude and longitude to their respective fields.
             if ($location) {
                update_field('latitude', $location['lat'], $post_id);
                update_field('longitude', $location['lng'], $post_id);
             }
          }
       }

    Replace 'your_custom_post_type' with the actual post type associated with your ACF field group.

    Conclusion: Latitude and Longitude with ACF Google Map

    By incorporating separate latitude and longitude fields alongside the ACF Google Map field and implementing the provided code snippets, you can effortlessly enhance your WordPress site’s ability to store and retrieve location data. This approach not only optimizes location-based queries but also streamlines the process of working with geospatial information in your applications.

    If you need help doing radius searches on ACF Google map data get in touch.

    Photo by Dariusz Sankowski on Unsplash

  • Outputting ACF GOOGLE MAP Data to Your WordPress Site

    Outputting ACF GOOGLE MAP Data to Your WordPress Site

    Introduction Outputting ACF GOOGLE MAP Data:

    The Advanced Custom Fields (ACF) Google Map field is a game-changer for websites that require location-based data visualization. In this blog post, we’ll guide you through the process of outputting ACF Google Map data to the front end of your WordPress site, turning coordinates into interactive maps for your users to explore. Let’s dive into the implementation details with some helpful code snippets.

    Setting Up ACF Google Map Field:

    Before we jump into the code, ensure you have the ACF plugin installed and activated on your WordPress site. Create a custom field group with a Google Map field, configuring it to meet your specific needs. Note that the field should be associated with the post type or page where you want to display the map.

    Outputting ACF Google Map Data to Frontend:

    1. Retrieve ACF Google Map Data: Use the ACF get_field function to retrieve the map data associated with a post or page. Ensure that you replace 'your_map_field_name' with the actual name of your Google Map field.
       <?php
       $map_data = get_field('your_map_field_name');
       ?>
    1. Outputting the Map: Once you have the map data, you can output it on the frontend using HTML and JavaScript. ACF provides a helpful function, acf_get_location, that can be used to format the map data.
       <?php
       $location = acf_get_location($map_data);
       ?>
       <div id="map-container">
          <div id="map" data-lat="<?php echo esc_attr($location['lat']); ?>" data-lng="<?php echo esc_attr($location['lng']); ?>"></div>
       </div>
    1. Adding JavaScript for Interactivity: To make the map interactive, you’ll need to include some JavaScript. This can be done using the Google Maps API. Don’t forget to replace 'your_google_maps_api_key' with your actual API key.
       <script src="https://maps.googleapis.com/maps/api/js?key=your_google_maps_api_key&callback=initMap" async defer></script>
       <script>
          function initMap() {
             var mapElement = document.getElementById('map');
             var lat = parseFloat(mapElement.getAttribute('data-lat'));
             var lng = parseFloat(mapElement.getAttribute('data-lng'));
    
             var map = new google.maps.Map(mapElement, {
                center: { lat: lat, lng: lng },
                zoom: 15 // You can adjust the initial zoom level
             });
    
             var marker = new google.maps.Marker({
                position: { lat: lat, lng: lng },
                map: map,
                title: 'Marker Title'
             });
          }
       </script>

    This JavaScript code initializes the Google Map, places a marker at the specified coordinates, and adjusts the map’s center and zoom level.

    Conclusion Outputting ACF GOOGLE MAP Data:

    By following these steps and integrating the provided code snippets, you can effortlessly output ACF Google Map data to the frontend of your WordPress site. This not only adds a visual appeal but also enhances the user experience by providing an interactive way for visitors to explore location-based content on your website.

    Photo by T.H. Chia on Unsplash

  • Unleashing the Power of ACF Google Map Field: A Comprehensive Guide

    Unleashing the Power of ACF Google Map Field: A Comprehensive Guide

    Introduction acf google maps:


    The Advanced Custom Fields (ACF) plugin has long been a favourite among WordPress developers for its flexibility in creating custom fields and meta-boxes effortlessly. One of the standout features of ACF is the Google Map field, which adds a whole new dimension to content creation and user engagement. In this blog post, we will delve into the ACF Google Map field, exploring its capabilities, implementation, and the myriad ways it can enhance your website.

    Understanding ACF Google Map Field:

    The ACF Google Map field is designed to simplify the process of integrating interactive maps into your WordPress website. Whether you’re creating a business directory, a travel blog, or a real estate website, this field type can elevate your content by allowing you to associate locations with posts, pages, or custom post types.

    Key Features:

    1. User-Friendly Interface:
      The ACF Google Map field provides an intuitive interface for users to pinpoint locations directly on the map. This ensures accuracy and eliminates the need for users to input latitude and longitude manually.
    2. Customization Options:
      ACF allows you to customize the appearance of the map, choosing from various map styles and controls. This ensures that the map seamlessly integrates with your website’s design.
    3. Geolocation and Address Search:
      Users can enter an address or use geolocation to automatically populate the map. This feature is particularly useful for applications where the user’s location is relevant, such as in-store locators or event planning.

    Implementation:

    1. Setting up ACF Google Map Field:
    • Install and activate the ACF plugin on your WordPress site.
    • Create a custom field group and add a new Google Map field.
    • Configure the field settings, including map center, default zoom level, and customization options.
    1. Displaying the Map on the Frontend:
    • Integrate the ACF Google Map field into your theme or template files using the ACF functions.
    • Retrieve and display the map data within your desired loop or content area.

    Use Cases:

    1. Location-Based Directories:
      Build robust business directories, store locators, or event listings by associating a Google Map with each entry. Users can easily find and visualize the location.
    2. Real Estate Websites:
      Enhance property listings by including an interactive map that showcases the exact location of each property. This provides potential buyers with a better understanding of the property’s surroundings.
    3. Travel Blogs:
      Create engaging travel blogs by adding maps to showcase the places you’ve visited. Users can click on markers to reveal more information about each location.

    Conclusion acf google maps:

    The ACF Google Map field is a powerful tool that adds a dynamic and interactive element to your WordPress website. Its versatility makes it suitable for a wide range of applications, providing a seamless way to integrate location-based information into your content. Whether you’re a developer looking to streamline the creation of custom fields or a website owner aiming to enhance user experience, the ACF Google Map field is a valuable addition to your toolkit.

    If you need help implementing Google maps on your WordPress site please get in touch.

    Photo by GeoJango Maps on Unsplash

  • CASE STUDY: ACF Google Map Radius Search

    CASE STUDY: ACF Google Map Radius Search

    In this case study I’ll walk through how I was able to create a radius search from Google map data for a client.

    It’s a bit technical if you just want to see the output, scroll down to the video for a demo of the front end.

    My clients requirement was for a user to enter their Zip code and then for the code to search on a custom post type called location and return all locations within a 100 mile radius.

    We had attached an ACF google map field to the custom post type so we could save the address data of the location on the post, I created a map and I could output all of the data points on the map, so far so good.

    Problem One – Google Maps Latitude and Longitude Data Is Serialised

    The data is serialised so it is very hard to search on an ACF google map, so I create two new fields (latitude and longitude) and upon save of the custom post type I grab the ACF field latitude and longitude and save them into their own fields.

    function nm_update_lat_long($post_id){
    	
    	$post_type = get_post_type( $post_id );
    
        if ( 'location' == $post_type ) {
    	
    		$xxx_map= get_field('xxx_google_map', $post_id);
    	
    		$_POST["acf"]["field_65b8c2e984961"]=$xxx_map['lat'];
    		$_POST["acf"]["field_65b8c2fb84962"]=$xxx_map['lng'];
    	
    		return $_POST;
    	}
    }
    
    add_action('acf/save_post', 'nm_update_lat_long',1);

    Convert Zip Code TO Co-Ordinates

    Using the Google maps API I can do a search using a zip code and return a set of latitude and longitude co-ordinates I can use to create my search are. The code looks like this.

    function nm_get_coords_zip_code($zip){
    	
    	
    	$api_key=get_field('xxx_options_google_map_api_key','options'); 
    	$url = "https://maps.googleapis.com/maps/api/geocode/json?address=".$zip."&sensor=false&key=".$api_key;
            $details=file_get_contents($url);
            $result = json_decode($details,true);
            $account_lat=$result['results'][0]['geometry']['location']['lat'];
            $account_long=$result['results'][0]['geometry']['location']['lng'];
    	return array($account_lat,$account_long);
    	
    }

    The Search Box

    Using maths I’ve not used since school, I was able to return a box which is 100 miles radius of my zip code. Who am I kidding I found it on stack overflow.

    function nm_getBoundingBox($lat_degrees,$lon_degrees,$distance_in_miles) {
    
        $radius = 3963.1; // of earth in miles
    
        // bearings - FIX   
        $due_north = deg2rad(0);
        $due_south = deg2rad(180);
        $due_east = deg2rad(90);
        $due_west = deg2rad(270);
    
        // convert latitude and longitude into radians 
        $lat_r = deg2rad($lat_degrees);
        $lon_r = deg2rad($lon_degrees);
    
        // find the northmost, southmost, eastmost and westmost corners $distance_in_miles away
        // original formula from
        // http://www.movable-type.co.uk/scripts/latlong.html
    
        $northmost  = asin(sin($lat_r) * cos($distance_in_miles/$radius) + cos($lat_r) * sin ($distance_in_miles/$radius) * cos($due_north));
        $southmost  = asin(sin($lat_r) * cos($distance_in_miles/$radius) + cos($lat_r) * sin ($distance_in_miles/$radius) * cos($due_south));
    
        $eastmost = $lon_r + atan2(sin($due_east)*sin($distance_in_miles/$radius)*cos($lat_r),cos($distance_in_miles/$radius)-sin($lat_r)*sin($lat_r));
        $westmost = $lon_r + atan2(sin($due_west)*sin($distance_in_miles/$radius)*cos($lat_r),cos($distance_in_miles/$radius)-sin($lat_r)*sin($lat_r));
    
    
        $northmost = rad2deg($northmost);
        $southmost = rad2deg($southmost);
        $eastmost = rad2deg($eastmost);
        $westmost = rad2deg($westmost);
    
        // sort the lat and long so that we can use them for a between query        
        if ($northmost > $southmost) { 
            $lat1 = $southmost;
            $lat2 = $northmost;
    
        } else {
            $lat1 = $northmost;
            $lat2 = $southmost;
        }
    
    
        if ($eastmost > $westmost) { 
            $lon1 = $westmost;
            $lon2 = $eastmost;
    
        } else {
            $lon1 = $eastmost;
            $lon2 = $westmost;
        }
    
        return array($northmost, $southmost, $eastmost, $westmost);
    }

    The Query

    I setup a query to search the data looking for locations within the bounds of the co-ordinates I had grabbed from the search box in the previous step. I saved those co-ordinates in an erray $distance_box. Here are the query arguments I used.

    $args = array(
    	'post_type'	=> 'location',
    	'post_status' => 'publish',	
    	
    	'meta_query'	=> array(
    		 'relation' => 'AND', 
    		
    		array(
    			'key'		=> 'xxx_latitude',
    		
    			'value'		=> array($distance_box[1]),
    			'compare'	=> '>=',
    			'type' => 'NUMERIC',
    		),
    		
    				array(
    			'key'		=> 'xxx_latitude',
    			'value'		=> array($distance_box[0]),
    			'compare'	=> '<=',
    			'type' => 'NUMERIC',
    		),
    		
    		
    		array(
    			'key'		=> 'xxx_longitude',
    		
    			'value'		=> array($distance_box[2]),
    			'compare'	=> '<=',
    			'type' => 'NUMERIC',
    		),
    		
    				array(
    			'key'		=> 'xxx_longitude',
    			'value'		=> array($distance_box[3]),
    			'compare'	=> '>=',
    			'type' => 'NUMERIC',
    		),
    		
    		
    	)	
    		
    	
    );

    Video Demo

    Here’s what it looks like on the front end.

    Wrap Up – Radius Search ACF Google Map Field

    So here’s my case study on how to search ACF google map fields via a 100 mile radius.

    If you need help implementing Google maps on your site please get in touch.

    Photo by José Martín Ramírez Carrasco on Unsplash

  • Troubleshooting Guide: Fixing WordPress 404 Errors on Sub-Pages by Flushing Permalinks

    Troubleshooting Guide: Fixing WordPress 404 Errors on Sub-Pages by Flushing Permalinks

    Introduction – Fixing WordPress 404 Errors on Sub-Pages

    Encountering 404 errors on sub-pages of your WordPress site can be a frustrating experience, especially when the main page is accessible. Fortunately, one common solution to this issue is to flush permalinks. In this troubleshooting guide, we’ll walk you through the steps to resolve the problem and restore access to your WordPress sub-pages.

    Identifying the Issue:

    1. Confirming the Problem:
    • Access the main page of your WordPress site. If it loads correctly, but sub-pages return 404 errors, it’s likely a permalink issue.
    1. Checking Permalink Settings:
    • Log in to your WordPress admin dashboard.
    • Navigate to “Settings” and select “Permalinks.”
    • Confirm your permalink structure settings and check if any recent changes were made.

    Resolving the Issue:

    1. Flushing Permalinks:
    • The primary solution to address 404 errors on sub-pages is to flush permalinks.
    • Navigate to “Settings” and select “Permalinks” in the admin dashboard.
    • Without making any changes, click the “Save Changes” button.
    • This action refreshes the permalink structure, resolving potential conflicts.
    1. Checking .htaccess File:
    • Ensure that your site’s root directory contains an .htaccess file.
    • Verify the file’s permissions and make sure it is writable.
    • If the file is missing, you can create a new one and add the default WordPress .htaccess rules.
    1. File and Folder Permissions:
    • Incorrect file or folder permissions might lead to 404 errors.
    • Check and ensure that the directories have a permission level of 755 and files are set to 644.
    • Consult your hosting provider or server documentation for guidance on setting permissions.
    1. Deactivating Plugins:
    • Some plugins can interfere with permalinks and cause 404 errors.
    • Temporarily deactivate all plugins and check if the issue persists.
    • If the problem resolves, reactivate plugins one by one to identify the culprit.
    1. Reviewing Theme Compatibility:
    • Switch to a default WordPress theme (e.g., Twenty Twenty-One) to rule out theme-related issues.
    • If the problem disappears with the default theme, there may be a conflict in your current theme’s functions.
    1. Checking for URL Conflicts:
    • Ensure there are no conflicting URLs or slugs.
    • Check for duplicate page or post slugs, as this can lead to conflicts.
    • Update the slugs or change the permalink structure if needed.
    1. Rebuilding Permalinks via FTP:
    • Access your site’s files using FTP.
    • Locate the .htaccess file in the root directory.
    • Rename the file to something else (e.g., .htaccess_old).
    • Go back to the Permalinks settings in the WordPress admin and click “Save Changes” to generate a new .htaccess file.

    Prevention:

    1. Regular Backups:
    • Implement regular backups of your WordPress site, including both files and the database, to restore quickly if issues arise.
    1. Plugin and Theme Updates:
    • Keep plugins and themes up to date to ensure compatibility with the latest WordPress version.

    Conclusion Fixing WordPress 404 Errors on Sub-Pages:

    Troubleshooting 404 errors on sub-pages in WordPress can often be resolved by flushing permalinks. Following the steps outlined in this guide should help you identify and address the issue efficiently. If the problem persists, consider seeking assistance from your hosting provider or a WordPress support community. Regular maintenance, backups, and staying informed about updates can contribute to a smoother WordPress experience.

    If you need help troubleshooting a problem on your WordPress site please get in touch.

    Photo by Erik Mclean on Unsplash

  • A Guide to Configuring Permalink Types in WordPress: Choose the Perfect URL Structure for Your Website

    A Guide to Configuring Permalink Types in WordPress: Choose the Perfect URL Structure for Your Website

    Introduction Guide to Configuring Permalink:

    Permalinks, the permanent URLs that point to your WordPress site’s pages and posts, are a crucial element of your website’s overall structure. WordPress offers various permalink types, allowing you to customize your URL structure to meet the specific needs of your content and improve SEO. In this blog post, we’ll explore the different permalink types available in WordPress and guide you through the process of configuring them for your website.

    Understanding Permalink Types:

    1. Default Permalinks:
      WordPress defaults to a simple structure that includes a page or post ID. While functional, these URLs are not user-friendly or SEO-optimized.
    2. Day and Name:
      This permalink type includes the publication date and post/page name. It’s beneficial for blogs or websites where the publication date is relevant.
    3. Month and Name:
      Similar to Day and Name, this structure excludes the day, resulting in shorter URLs while retaining some chronological information.
    4. Numeric:
      This permalink type includes only the post or page ID, providing a concise and clean URL structure.
    5. Post Name:
      Widely popular, Post Name structures URLs based on the title of the post or page. This creates clean, human-readable URLs, making it a preferred choice for SEO.
    6. Custom Structure:
      For maximum flexibility, you can create a custom permalink structure using various placeholders, such as %postname%, %category%, or %year%. This allows you to craft a URL format that suits your specific needs.

    Configuring Permalink Types:

    1. Accessing Permalink Settings:
    • Log in to your WordPress admin dashboard.
    • Navigate to “Settings” and select “Permalinks.”
    1. Choosing a Permalink Structure:
    • On the Permalinks settings page, you’ll find the different permalink options.
    • Select the structure that best suits your content and SEO strategy.
    1. Customizing the Permalink Structure:
    • If you choose the “Custom Structure” option, you can define your own format using placeholders.
    • For example, using /%category%/%postname%/ in the custom structure would include the category and post name in the URL.
    1. Saving Changes:
    • After selecting or customizing your preferred permalink structure, scroll down and click “Save Changes” to apply the new settings.

    Considerations and Best Practices:

    1. SEO Impact:
    • Choose a permalink structure that is SEO-friendly, emphasizing keywords relevant to your content.
    1. User Experience:
    • Prioritize a permalink structure that enhances user experience, making it easy for visitors to understand the content hierarchy.
    1. Avoiding Common Pitfalls:
    • Steer clear of changing your permalink structure frequently, as this can lead to broken links. If changes are necessary, set up proper redirects.
    1. Redirects for Existing Content:
    • If you’re changing your permalink structure on an existing site, implement redirects to ensure that old URLs still lead to the correct content.

    Conclusion: Guide to Configuring Permalink

    Configuring permalink types in WordPress is a fundamental step in optimizing your website for both users and search engines. Whether you prefer a clean and simple Post Name structure or opt for a custom format to include additional information, understanding the available options and their implications is key. By carefully selecting and configuring your permalink structure, you can create a website with URLs that are both user-friendly and optimized for search engine visibility.

    If you need help with permalinks please get in touch.