简体   繁体   English

在 wordpress 中获取用户的经纬度

[英]get latitude and longitude of a user in wordpress

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.我在 html+css+php 页面中有一个“经典”的 js 脚本,当单击表单中的搜索按钮时,它会获取客户端的纬度和经度。 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/bootstrap@5.2.0-beta1/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/bootstrap@5.2.0-beta1/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.这做得很好,现在我想在 wordPress 中做同样的事情,我创建了自己的搜索表单进行测试,但我不知道如何让 js corray 返回结果我这么说是因为变量 tatitude 和 longitude 到达空的。

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.我在子主题的functions.php中添加了以下内容。 and I have the form in the header, also this code in the header我在 header 中有表格,在 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: header中的表格如下:

<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.这种情况是到达目的地 url 的变量没有值到达。

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.我想要什么,如果可能的话,告诉我是否有另一种方法来放置用户的纬度和经度(如果我的不够)我也有一个细节,它是对 maps.js 文件的调用(我没有不知道如何调用链接谷歌外部。

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

Forgive my high ignorance in advance提前原谅我的高度无知

Just use this plugin User IP and Location .只需使用这个插件User IP 和 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).它还有您需要的另一个短代码(检查上面的链接)。

I have found a "partial detail" solution.我找到了一个“部分细节”的解决方案。 I have created a function in javascript and call it directly.我在 javascript 中创建了一个 function 并直接调用它。 I transcribe the function detail below.我在下面转录 function 详细信息。 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现在我有两个问题 1.- 精度表明客户位置很远(我必须看看如何提高这个精度) 2.- 第一次发送表单时,它用空数据发送它,它只来自第二个搜索它目前的值(这是一个大问题)我不知道如何解决这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM