【问题标题】:How to get current latitude and longitude in php using google map api?如何使用google map api在php中获取当前的纬度和经度?
【发布时间】:2016-02-15 23:44:14
【问题描述】:

如何使用 google map api 在 php 中获取当前经纬度? 我正在尝试使用 HTML5 获取纬度和经度,但我无法获取函数外的变量。请分享一些知识关于这个。

$(document).ready(function () {
    var latitude = ''; var longitude = '';

    if(navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function(position) {
         latitude = position.coords.latitude;
         longitude = position.coords.longitude;
        }, function() {
          alert("Geolocation Failed");
        });
    }
    console.log(longitude); // I am trying to console this variable here but its print blank;
});

【问题讨论】:

    标签: javascript php google-maps


    【解决方案1】:

    您应该在成功回调中移动控制台日志行: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition

    换句话说,您必须等待 getCurrentPosition 的执行给您一个结果。

    【讨论】:

    • 问题即将在该函数之外的变量中获取值
    • 好的,但我不认为这是可能的,这是一个带有回调的函数,因此您只能在位置结果可用时使用它。在成功回调中,您可以简单地调用“processResult()”函数并从那里继续并在该点操作经度变量
    • 其实我也面临这种问题,我有一个php文件,我需要代表当前的lat和lang执行sql查询,我试图通过IP获取lat lang但是这是不正确的。我没有得到任何解决方案将此脚本与我的 php-mysql 查询一起使用
    • 您可以在“processResult()”函数中放置一个 AJAX 请求,该函数指向一个执行 SQL 查询的 PHP 脚本
    • @Mat 谢谢你的建议 :)
    【解决方案2】:

    您可以使用 jQuery 将经度和经度存储到 cookie 或会话中,并在其他任何地方使用。

    例如:

    var sess_longitude = localStorage[longitude];
    

    【讨论】:

    • 它是一个很好的解决方案,并解决了我的问题,因为我可以使用 cookie 并在 php 变量中使用它。感谢您的想法:)
    【解决方案3】:
    <?php 
    
    $page = 'map';
    $bodyClass = 'map-page';
    include "includes/header.php";
    
    ?>
    <style>
      #map {
        height: 100%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    <div class="card content-card">
        <header class="card-header">
            <a href="javascript:history.go(-1)" class="btn-icon btn-icon-primary btn-bar"><i class="far fa-arrow-left"></i></a>
            <h3 class="page-title">Add Address</h3>
            
            <div class="right-menu">
                <a href="#" class="btn-icon btn-icon-primary btn-lang">
                    <svg class="icon-lang" width="1em" height="1em" viewBox="0 0 32 32">
                        <path fill-rule="evenodd" d="M22 22.424c-1.099.95-2.388 1.675-3.868 2.174-.952.268-1.919.402-2.901.402-1.48 0-2.721-.399-3.725-1.197C10.502 23.006 10 21.711 10 19.921c0-.743.117-1.463.35-2.16.233-.698.65-1.403 1.252-2.115.289-.317.505-.553.65-.708.144-.155.271-.266.382-.333-.792-.683-1.188-1.346-1.188-1.992-.03-.749.497-1.857 1.584-3.325C13.779 8.429 14.605 8 15.507 8c.455 0 .91.132 1.368.397.457.265.792.488 1.004.667.212.18.39.375.534.585.144.21.216.412.216.607-.006.03-.021.046-.046.046-.847-.305-1.565-.457-2.155-.457-.233 0-.532.054-.898.16-.365.107-.744.3-1.137.58-.393.28-.59.563-.59.85 0 .286.274.59.82.913.547.323.875.506.986.548.233-.03 1.092-.231 2.578-.603l1.073-.205c.237-.046.557-.117.963-.215l-.857 2.64h-.064c-.24 0-.792.085-1.658.256-4.163.962-6.244 2.552-6.244 4.768 0 .396.224.84.672 1.334.995.719 2.22 1.163 3.675 1.334.46.085.878.14 1.252.164.375.025 1.02.052 1.934.082A122.29 122.29 0 0122 22.424z"></path>
                    </svg>
                </a>
                <a href="" class="btn-icon btn-icon-primary btn-cart"><i class="far fa-shopping-bag"></i></a>
            </div>
        </header>
        
        <div id="map"></div>
        
        <div class="card-footer border-0 px-20">
            <form action="<?=base_url()?>checkout/addaddress" method="POST">
                <input type="hidden" id="lat" name="lat">
                <input type="hidden" id="long" name="long">
                <input type="submit" name="submit" class="btn btn-primary btn-block" value="Add Address">
            </form>
            <a href="<?=base_url()?>checkout/skipaddress" class="btn btn-default btn-block"> Skip </a>
        </div>
    </div>
    <!-- End your project here-->
    
    <script>
         function locate(){
            if ("geolocation" in navigator){
                navigator.geolocation.getCurrentPosition(function(position){ 
                    var currentLatitude = position.coords.latitude;
                    var currentLongitude = position.coords.longitude;
    
                    var infoWindowHTML = "Latitude: " + currentLatitude + "<br>Longitude: " + currentLongitude;
                    var infoWindow = new google.maps.InfoWindow({map: map, content: infoWindowHTML});
                    var currentLocation = { lat: currentLatitude, lng: currentLongitude };
                    infoWindow.setPosition(currentLocation);
                    $("#lat").val(currentLatitude);
                    $("#long").val(currentLongitude);
                });
            }
        }
    </script>
    
    <script>
          var myLatlng,map;
          function initMap() {
              locate();
    
          //myLatlng = {lat: 21.2130653, lng: 72.8402571};
    
          map = new google.maps.Map(
              document.getElementById('map'), {
                zoom: 20,
                center: myLatlng,
                //streetViewControl: 0
              });
          let markers = [];
    
          marker = new google.maps.Marker({
              position: myLatlng,
              map,
              title: "Your Location"
            });
            markers.push(marker);
    
          infoWindow = new google.maps.InfoWindow;
    
            // Try HTML5 geolocation.
            if (navigator.geolocation) {
              navigator.geolocation.getCurrentPosition(function(position) {
                var myLatlng = {
                  lat: position.coords.latitude,
                  lng: position.coords.longitude
                };
    
                document.getElementById('lat').value=position.coords.latitude;
                document.getElementById('long').value=position.coords.longitude;
                map.setCenter(myLatlng);
                map.setZoom(18);
                //map.setStreetView(0);
              
                marker = new google.maps.Marker({
                  position: myLatlng,
                  map,
                  title: "Your Location"
                });
                markers.push(marker);
    
              }, function() {
                handleLocationError(true, infoWindow, map.getCenter());
              });
            } else {
              // Browser doesn't support Geolocation
              handleLocationError(false, infoWindow, map.getCenter());
            }
    
            map.addListener('click', function(mapsMouseEvent) {
          // Close the current InfoWindow.
          for (let i = 0; i < markers.length; i++) {
              markers[i].setMap(null);
            }
            markers = [];
          // Create a new InfoWindow.
    
            var string = mapsMouseEvent.latLng.toString();                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            var array = string.split(",");
            var lat = array[0].substring(1);
            var dsfsd = array[1].trim();
            var long = dsfsd.substring(0,dsfsd.length-1);
          document.getElementById('lat').value=lat;
          document.getElementById('long').value=long;
    
            marker = new google.maps.Marker({
              position: mapsMouseEvent.latLng,
              map,
              title: "Your Location"
            });
          markers.push(marker);
        
        });
    
        marker.addListener("click", () => {
              infoWindow.open(map, marker);
            });
    
    
    
          }
    
          function handleLocationError(browserHasGeolocation, infoWindow, pos) {
            infoWindow.setPosition(pos);
            infoWindow.setContent(browserHasGeolocation ?
                                  'Error: The Geolocation service failed.' :
                                  'Error: Your browser doesn\'t support geolocation.');
            infoWindow.open(map);
          }
        </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCuHX1kolcnapKN-MAW_hhgOLPXEbHVKQA&callback=initMap"></script>
    <?php include "includes/footer.php"; ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-31
      • 2017-05-07
      • 2015-09-24
      • 1970-01-01
      相关资源
      最近更新 更多