简体   繁体   中英

How to send the value of a Python variable to JavaScript in HTML

I am using the Google App Engine to display a Google map on a web page.

I want to bring the latitude and longitude in the database and display it on the map. To do this, I need to pass the imported latitude and longitude to JavaScript in HTML. I have tried several ways but it is useless. (ex. {{variable}} is useless.)

How best to debug or otherwise proceed on this?

class Map(webapp2.RequestHandler):

    db = connect_to_cloudsql()
    cursor = db.cursor()
    cursor.execute("""select latitude,longitude from User;""")

    data=cursor.fetchone() 
    lat=data[0]
    lng=data[1]

    formstring = """
    <!DOCTYPE html> 
    <html lang="ko-KR">
    <head>
    <meta charset="utf-8"/>
        <meta name="google-site-verification" content="9EqLgIzCmwFo7XAcSe4sBNZ_t0gULadyeF9BCO0DY3k"/>
    </head>
    <body class>
    <style>
     #map {
        width: 80%;
        height: 400px;
        background-color: grey;
      }
    </style>
    <div style="position:relative;width:1080px;margin:0 auto;z-index:11">
    <div class="container" role="main">
    <div id="map"></div>
    <br><br>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=mykey&callback=initMap">
    </script>
     <script>
      function initMap() {

        var uluru = {lat: {lat} , lng: {lng} };
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: uluru
        });
        var marker = new google.maps.Marker({
          position: uluru,
          map: map
        });
      }
    </script>

    </div>
    </div>
    </body>
    </html>
        """

Take a look at string formatters . As you grow your web app, you'll probably want to switch to using templates because they are more robust. Webapp2 provides support for Jinja2 templates , which are widely used and will make your life easier in the long run.

But in the short run, use string formatters:

formstring = """
<!DOCTYPE html> 
...

    var uluru = {lat: %f , lng: %f };
    var map = new google.maps.Map(document.getElementById('map'), {
...
""" % (lat, lng)  # assuming lat/lng are floats, use %s instead of %f for strings

Alternatively, use the "new way":

formstring = """<html.......{lat: {:f}, lng: {:f}...""".format(lat, lng)

Again, look at string formatters .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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