Python Flask GoogleMaps获取用户当前位置纬度和经度

时间:2017-05-27 15:50:39

标签: python google-maps flask

我正在使用Python和Flask构建一个webapp,并将flask-googlemaps作为我的最后一页。至于最后一页,我需要获取用户当前位置的纬度和经度。

这是我的run.py

# coding: utf-8

from flask import Flask, render_template
from flask_googlemaps import GoogleMaps
from flask_googlemaps import Map, icons
import webbrowser

app = Flask(__name__, template_folder="templates")

GoogleMaps(app, key="my-key")

@app.route('/')
def mymap():
    mymap = Map(
                identifier="view-side",
                varname="mymap",
                style="height:720px;width:1100px;margin:0;", # hardcoded!
                lat=37.4419, # hardcoded!
                lng=-122.1419, # hardcoded!
                zoom=15,
                markers=[(37.4419, -122.1419)] # hardcoded!
            )
    return render_template('example_mymap.html', mymap=mymap)


if __name__ == "__main__":
    webbrowser.open('http://127.0.0.1:5000')
    app.run(debug=True, use_reloader=True)

这是我的example_mymap.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Flask Google Maps Example</title>
        <link rel="stylesheet" href="/static/css/bootstrap.min.css">
        {{mymap.js}}
    </head>
    <body>
        <div class="container">
            <h1>Flask Google Maps Example</h1><hr>
            {{ mymap.html }}
        </div>
    </body>
</html>

试图搜索并获得很少的解决方案。试过这个,https://developers.google.com/maps/documentation/javascript/examples/map-geolocation但它没有用。在我的模板主体中添加以下脚本没有任何结果。

    <script>
      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map, infoWindow;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 6
        });
        infoWindow = new google.maps.InfoWindow;

        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            infoWindow.open(map);
            map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }
      }

      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 async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>

尝试了来自此主题的解决方案,Getting map location Python但是,效果不佳。它给了我一条错误消息,说明这段代码latlon = re.search("GPoint\(([^)]+)\)",raw).groups(0)None。以下是确切的错误消息AttributeError: 'NoneType' object has no attribute 'groups'

# coding: utf-8

from flask import Flask, render_template
from flask_googlemaps import GoogleMaps
from flask_googlemaps import Map, icons
import webbrowser

app = Flask(__name__, template_folder="templates")

GoogleMaps(app, key="my-key")

def get_current_location_lat_and_long(url):
    import re, requests

    raw = requests.get(url).text
    latlon = re.search("GPoint\(([^)]+)\)",raw).groups(0)
    lat,lon = map(float,latlon[0].split(","))
    return lat,lon

@app.route('/')
def mymap():

    cur_lat, cur_lng = get_current_location_lat_and_long(url='http://www.geoiptool.com/')

    mymap = Map(
                identifier="view-side",
                varname="mymap",
                style="height:720px;width:1100px;margin:0;", # hardcoded!
                lat=cur_lat,
                lng=cur_lng,
                zoom=15,
                markers=[(cur_lat,cur_lng)]
            )
    return render_template('example_mymap.html', mymap=mymap)


if __name__ == "__main__":
    webbrowser.open('http://127.0.0.1:5000')
    app.run(debug=True, use_reloader=True)

有人可以建议我另一个解决方案吗?任何建议将不胜感激。非常感谢。

1 个答案:

答案 0 :(得分:3)

我也试图创建网络应用程序,所以我被困在&#34;知道你的位置&#34;看到你的代码能够修改,并猜测它是什么工作!!

您修改的py文件

from flask import Flask, render_template

from flask_googlemaps import GoogleMaps

from flask_googlemaps import Map


app = Flask(__name__)


GoogleMaps(app, key="my-key")




@app.route('/', methods=["GET"])
def my_map():
    mymap = Map(

                identifier="view-side",

                varname="mymap",

                style="height:720px;width:1100px;margin:0;", # hardcoded!

                lat=37.4419, # hardcoded!

                lng=-122.1419, # hardcoded!

                zoom=15,

                markers=[(37.4419, -122.1419)] # hardcoded!

            )

    return render_template('example.html', mymap=mymap)





if __name__ == "__main__":

    app.run(debug=True, use_reloader=True)

您修改过的HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map, infoWindow;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 6
        });
        infoWindow = new google.maps.InfoWindow;

        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            infoWindow.open(map);
            map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }
      }

      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 async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOURAPIKEY&callback=initMap">
    </script>
    <body>
        <div class="container">
            <h1>Flask Google Maps Example</h1><hr>
            {{ mymap.html }}
        </div>
    </body>
</html>