簡體   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