Getting App Inventor 2 variable values in an HTML/Javascript file

拈花ヽ惹草 提交于 2019-12-02 16:18:33

问题


I am setting up a simple map program for a user to see locations on an embedded Google map. I have the map working, but I was wondering if there is a way for the user to input coordinates in AI2 then have the map center there. Here is the HTML file I am using to display the map.

<!DOCTYPE html>
<html>
   <head>
     <meta charset="utf-8">
     <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
     <style type="text/css">
     html { height: 100% }
     body { height: 100%; margin: 0; padding: 0 }
     #map_canvas { height: 100% }
     </style>

     <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&sensor=true&language=en"></script>

     <script type="text/javascript">
  function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(-34.397, 150.644),
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
     };
     map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    // Add a listener for the click event
    google.maps.event.addListener(map, 'click', showPosition);
  }

  function showPosition(event) {
    // display a marker on the map
    marker = new google.maps.Marker({
      position: event.latLng,
      map: map,
      icon: "./marker.png"
    });

    // print the selected position to the page title
    var position = event.latLng.lat().toFixed(6) + ", " + event.latLng.lng().toFixed(6);
    window.document.title = position;
  }
</script>
  </head>
  <body onload="initialize()">
    <div id="map_canvas" style="width:100%; height:100%"></div>
  </body>
</html>

回答1:


Yes, that's possible.

You can use WebViewString to communicate values back and forth between your App and the WebViewer. In your App, you get and set the WebViewer.WebViewString properties. In your webviewer, you open to a page that has Javascript that references the window.AppInventor object, using its getWebViewString() and setWebViewString(text) methods.

See also the following snippet for a complete example.

<!doctype html>
<head>
  <meta name="author" content="puravidaapps.com">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test</title>
</head>
<body>
  <script>
    document.write("The value from the app is<br />" + window.AppInventor.getWebViewString());
    window.AppInventor.setWebViewString("hello from Javascript")
  </script>
</body>
</html>


来源:https://stackoverflow.com/questions/29292395/getting-app-inventor-2-variable-values-in-an-html-javascript-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!