简体   繁体   中英

Call Kotlin transpired Javascript function in plain Javascript

I have a Kotlin file say Sample.Kt which have just one function which gets the string as an input and do a rest call and return a response in array. I would like to call this method in my html file inside script tag.

Kotlin Code:

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)
            })
}

index.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>

If I call my Kotlin function inside a script tag, I'm getting the following error Uncaught ReferenceError: main is not defined .

Try add @JsName annotation like this

import kotlin.browser.window

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

This annotation forces K/JS compiler to allocate for annotated function specified name.

尝试

<your module name>.main(boundary)

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