繁体   English   中英

在纯 Javascript 中调用 Kotlin 发生的 Javascript 函数

[英]Call Kotlin transpired Javascript function in plain Javascript

我有一个 Kotlin 文件,比如 Sample.Kt,它只有一个函数,它获取字符串作为输入并执行一个休息调用并在数组中返回一个响应。 我想在脚本标记内的 html 文件中调用此方法。

科特林代码:

import kotlin.browser.window

fun main(boundaries: String) {
    console.log("Kotlin File")
    var smf: dynamic = js("({})")
    smf.method = "GET"
    smf.mode   = "cors"
    smf.cache  = "default"
    var url = "https://api/byBoundary?boundary=$boundaries&limit=500&aggregateType=parkingLocation&enrichWith=lotDetails"
    window.fetch(url, smf)
            .then({response ->
                console.log(response)
            })
            .catch({error ->
                console.error(error)
            })
}

索引.html

<!DOCTYPE html>
<html>
<head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <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>
    <script type="text/javascript" src="out/production/KotlinJs/lib/kotlin.js"></script>
    <script type="text/javascript" src="out/production/KotlinJs/KotlinJs.js"></script>
</head>
<body>
<h1>Hello</h1>
<div id="map"></div>
<script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 49.28046020235976, lng: -123.11303973197937},
          zoom: 15
        });

        map.addListener('idle', function(ev){
            // update the coordinates here
            var bounds = map.getBounds();
            var ne = bounds.getNorthEast(); // LatLng of the north-east corner
            var sw = bounds.getSouthWest(); // LatLng of the south-west corder

            console.log(ne.lat())
            console.log(sw.lng())
            console.log(sw.lat())
            console.log(ne.lng())
            /*
            var nw = new google.maps.LatLng(ne.lat(), sw.lng());
            var se = new google.maps.LatLng(sw.lat(), ne.lng());
            */
            var boundary = sw.lng() + "," + sw.lat() + "," + ne.lng() + "," + ne.lat();//
            //boundary = "-123.12991786748171,49.26615473457274,-123.11303973197937,49.28046020235976"
            var pbpApi = "https://api/byBoundary?boundary=" + boundary + "&limit=500&aggregateType=parkingLocation&enrichWith=lotDetails"
            console.log(pbpApi);
            callPbpGeoApi(pbpApi);
            //main(boundary); **I would like to call my Kotlin function here**
        });
      }


      function addMarkerFun(props){
        var marker = new google.maps.Marker({
            position: {lat: props.geometry.coordinates[1], lng: props.geometry.coordinates[0]},
            map: map
        });

        var infoWindow = new google.maps.InfoWindow({
            content: props.properties.lotDetails.name
        });

        marker.addListener('click', function(){
            infoWindow.open(map, marker);
        });
      }

      function callPbpGeoApi(url){
        fetch(url)
            .then((resp) => resp.json())
            .then(function(data){
                let locations = data;
                for(var i = 0; i < locations.length; i++){
                  addMarkerFun(locations[i]);
                }
            });
      }
    </script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD7vYuz1P1BzfcmSAl98uyAroweCxlDirI&callback=initMap"
        async defer></script>
</body>
</html>

如果我在脚本标签内调用我的 Kotlin 函数,我会收到以下错误Uncaught ReferenceError: main is not defined

尝试像这样添加@JsName注释

import kotlin.browser.window

@JsName("main")
fun main(boundaries: String) {
 /// ...
}

此注释强制K / JS编译器为注释函数指定名称。

尝试

<your module name>.main(boundary)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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