skip to Main Content

in principle thanks in advance for your collaboration in my illiteracy.
I have a js script in a html+css+php page that is "classic" and which obtains the latitude and longitude of the client when clicking a search button in a form.
I transcribe it for now to put them in context.

document.getElementById("search").addEventListener("keydown", getCoord);
 var latitud;
 var longitud;
    if (navigator.geolocation) {
            // Obtenemos la ubicacion
            obtener_localizacion();

        } else {
             alert("Tu navegador no soporta la geolocalización, actualiza tu navegador.");
        } 

        function obtener_localizacion() {
            navigator.geolocation.getCurrentPosition(coordenadas);
        }
            
        function coordenadas(position) {
            latitud = position.coords.latitude;
            longitud = position.coords.longitude;
            
           // alert('Tus coordenadas son: ('+latitud+','+longitud+')');
        }
        function getCoord(){
            //$('#latCte').add(latitud);
            document.getElementById('latCte').value = latitud;
            document.getElementById('lngCte').value = longitud;
            //alert (event.key);
            //alert('Tus coordenadas son: ('+latitud+','+longitud+')');
            //event.preventDefault();
        }  

in the same way I transcribe the form (it has no major case) but it is to show what I have done.

?>
<!DOCTYPE html>
<html lang = "ES_es">
    <head>
        <title>Busqueda</title>
        <meta charset = "UTF-8" />
              <!-- scripts css  -->
        <link href="/busco/css/estilo.css">
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
        

    </head>
<body>
    <h4 class = "text-primary">Busqueda</h4>
    <div class = "container-fluid"> 
        <form class = "form-inline" method="post" action="resultadoPrueba.php">
            <div class = "row">
                <div class = "col-md-4">
                    <hr class="hr-st"style = "border-top: 1px dotted #8c8b8b;"/>
                            <div class  =  "form-group">
                                <label>Busqueda:</label>
                                <input type="text" id = "search" class = "form-control" name = "search" required = "required">
                                <input type="hidden" id = "latCte"  name = "latCte" value=""  >
                                <input type="hidden" id = "lngCte"  name = "lngCte" value="">
                                <input type="submit" class="btn btn-primary" name="enviar" value="enviar" > 
                            </div>
                </div>
            </div>
        </form>
        
    </div>
</body>
<!--  scripts js -->
<!-- Buil:js  /js/*js  -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCtm1NkW3Zli_2Ecj02lCHiopghTdwhOxY>" async></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<script src="/busco/js/index.js"></script>
</html>

this does it well, now I would like to do the same in wordPress, I have created my own search form to test but I don’t know how to make the js corray return the result I say this because the variables tatitude and longitude arrive empty.

add_action('wp_enqueue_scripts', 'ach_custom_js');
function ach_custom_js() {
    wp_enqueue_script('custom', '/js/maps.js');
}

I have added the following in the functions.php of the child theme.
and I have the form in the header, also this code in the header

<?php
/* script en linea  */
add_action('wp_head', 'ach_script_wp_head');
function ach_script_wp_head() {
    ?>
        <script>
            document.getElementById("search").addEventListener("keydown", getCoord);
            var latitud;
            var longitud;
                if (navigator.geolocation) {
                        // Obtenemos la ubicacion
                        obtener_localizacion();

                    } else {
                        alert("Tu navegador no soporta la geolocalización, actualiza tu navegador.");
                    } 

                    function obtener_localizacion() {
                        navigator.geolocation.getCurrentPosition(coordenadas);
                    }
                        
                    function coordenadas(position) {
                        latitud = position.coords.latitude;
                        longitud = position.coords.longitude;
                        
                    // alert('Tus coordenadas son: ('+latitud+','+longitud+')');
                    }
                    function getCoord(){
                        //$('#latCte').add(latitud);
                        document.getElementById('latCte').value = latitud;
                        document.getElementById('lngCte').value = longitud;
                        //alert (event.key);
                        //alert('Tus coordenadas son: ('+latitud+','+longitud+')');
                        //event.preventDefault();
                    }   
        </script>
    <?php
}

the form in the header is as follows:

<form class = "products-search" method="post" action="url-destino">
    <div class="psearch-content">
        <div class = "search-wrapper">      
            <input type="text" id = "search" class = "search-field" name = "search" required = "required" placeholder="Estoy Buscando...oks">
            <input type="hidden" id = "latCte"  name = "latCte" value=""  >
            <input type="hidden" id = "lngCte"  name = "lngCte" value="">
        </div>
        <button type="submit" class="search-submit mf-background-primary" name="enviar">enviar</button>
    </div>
</form>

The case is that the variables to the destination url arrive without value.

What I want, if it is possible, tell me if there is another way to place the user’s latitude and longitude (if mine is not adequate) I also have a detail and it is the call to the maps.js file (I don’t know how to have a call to the link google external.

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCtm1NkW3Zli_2Ecj02lCHiopghTdwhOxY>" async></script>

Forgive my high ignorance in advance

2

Answers


  1. Chosen as BEST ANSWER

    I have found a "partial detail" solution. I have created a function in javascript and call it directly. I transcribe the function detail below. I think it is also a "classic" (when I refer to classic, I mean functions that there are spread on the net in one way or another)

    const watcher = navigator.geolocation.watchPosition(mostrarLat);
    const watcher2 = navigator.geolocation.watchPosition(mostrarLon);
    setTimeout(() => {navigator.geolocation.clearWatch(watcher);
            }, 15000);
    setTimeout(() => {navigator.geolocation.clearWatch(watcher2);
            }, 15000);
    
    function mostrarLat (ubicacion) {
        const lat = ubicacion.coords.latitude;
        var el = document.getElementById("lat");
        el.value = lat;
    }
    function mostrarLon (ubicacion) {
        const lon = ubicacion.coords.longitude;
        var doe = document.getElementById("lon");
        doe.value = lon;
    }
    
    

    now i have two problems 1.- the precision indicates a highly distant client location (I must see how to improve this precision) 2.- The first time the form is sent, it sends it with empty data and it is only from the second search that it takes the value (this is a big problem) at the moment I don't know how to solve this


  2. Just use this plugin User IP and Location.
    It has shortcode to get latitude and longitude:

    [userip_location type="lat"]
    [userip_location type="lon"]
    

    It also has another shortcodes you need (check the link above).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search