duanbu9345 2016-09-15 12:32
浏览 110
已采纳

从Google Geolocation API获取当前的lat和lng

I have no problem getting the current lat and lng using javascript. But I would like to call the API link in PHP via file_get_contents as following:

<?php
$json = file_get_contents('https://www.googleapis.com/geolocation/v1/geolocate?key=Jsddds6s6sdht43asdsaASasta8962');
?>

Current if I paste the URL in Chrome, I am getting Not Found. Why does this happened?

  • 写回答

2条回答 默认 最新

  • dongzhao1865 2016-09-15 13:14
    关注

    Its giving error because your are use query string GET method for it

    use POST method to retrieve data because google geolocation only allows post method enter image description here here is an example

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Geocode  Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
      <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
     
    </head>
    <body>
    <span>Your Latitude : </span><span id="lat"></span><br>
    <span>Your Longitude : </span><span id="lng"></span><br>
    <button id="btn">Click Here To Get Lat And Lng</button>
    <script>
    $(document).ready(function() {
        $('#btn').click(function(e) {
             $.ajax({
            type : 'POST',
            data: '', 
            url: "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCW0lvagDP67ulkwwP7yAIBHJoj2HT0apM", 
            success: function(result){
                    $('#lat').html(result['location']['lat']);
                    $('#lng').html(result['location']['lng']);
                        
                }});
                        
        });
    } );
    </script>
    
    </body>
    </html>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?