从java代码中调用javascript中的谷歌地图功能

时间:2016-03-27 05:04:25

标签: javascript java google-maps google-maps-api-3 exception-handling

基本上我想使用 Test.java index.js 调用 initMap 方法,以便从起始列表到目的地的最短距离。

但是,当我运行 Test.class 时, 它显示ReferenceError: "Google" is not defined in <eval> at line number 10 该行为var bounds = new google.maps.LatLngBounds;

enter image description here

 public class Test {

    public static void main(String []args) throws ScriptException, IOException, NoSuchMethodException {
        String[] addres = new String[3];

       call("Airport Blvd, Singapore",new String[]{"50 Nanyang Ave, 639798 Singapore","21 Lower Kent Ridge Rd, 119077, Singapore","81 Victoria St, Singapore"});
    }
    public static void call(String s, String [] sarr)throws ScriptException, IOException, NoSuchMethodException{
        StringBuilder sb = new StringBuilder();
        sb.append(s+"*");
        for(String element:sarr){
            sb.append(element + "*");
        }
        System.out.println(sb.toString().substring(0, sb.toString().length()-1));
        ScriptEngineManager manager = new ScriptEngineManager();

        ScriptEngine engine = manager.getEngineByName("JavaScript");
        // read script file
        engine.eval(Files.newBufferedReader(Paths.get("/Projects/GetShortestDistance/index.js"), StandardCharsets.UTF_8));

        Invocable inv = (Invocable) engine;
        // call function from script file

      System.out.println("Testing:"+ inv.invokeFunction("initMap", sb.toString()));

    }

}

以下是我的javascript参考Google Developer

function initMap(longstr) {
    var bounds = new google.maps.LatLngBounds;
    var markersArray = [];

   // longstr ='Airport Blvd, Singapore*21 Lower Kent Ridge Rd, 119077, Singapore*50 Nanyang Ave, 639798 Singapore*80 Mandai Lake Rd, 729826*551 bukit timah road'
    var array = longstr.split('*');

    var destination = array[0];
    var origins1 = [];
    for(var i =1; i<array.length;i++){
        origins1.push(array[i]);
    }

    var min = "";
    var minAddress = null;


    var destinationIcon = 'https://chart.googleapis.com/chart?' +
        'chst=d_map_pin_letter&chld=D|FF0000|000000';
    var originIcon = 'https://chart.googleapis.com/chart?' +
        'chst=d_map_pin_letter&chld=O|FFFF00|000000';
    var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 55.53, lng: 9.4},
        zoom: 10
    });
    var geocoder = new google.maps.Geocoder;

    var service = new google.maps.DistanceMatrixService;
    service.getDistanceMatrix({
        origins: [origin1, origin2],
        destinations: [destinationA, destinationB],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
    }, function(response, status) {
        if (status !== google.maps.DistanceMatrixStatus.OK) {
            alert('Error was: ' + status);
        } else {
            var originList = response.originAddresses;
            var destinationList = response.destinationAddresses;
            var outputDiv = document.getElementById('output');
            outputDiv.innerHTML = '';
            deleteMarkers(markersArray);

            var showGeocodedAddressOnMap = function(asDestination) {
                var icon = asDestination ? destinationIcon : originIcon;
                return function(results, status) {
                    if (status === google.maps.GeocoderStatus.OK) {
                        map.fitBounds(bounds.extend(results[0].geometry.location));
                        markersArray.push(new google.maps.Marker({
                            map: map,
                            position: results[0].geometry.location,
                            icon: icon
                        }));
                    } else {
                        alert('Geocode was not successful due to: ' + status);
                    }
                };
            };

            for (var i = 0; i < originList.length; i++) {
                var results = response.rows[i].elements;
                geocoder.geocode({'address': originList[i]},
                    showGeocodedAddressOnMap(false));
                for (var j = 0; j < results.length; j++) {
                    geocoder.geocode({'address': destinationList[j]},
                        showGeocodedAddressOnMap(true));
                    outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
                        ': ' + results[j].distance.text + ' in ' +
                        results[j].duration.text + '<br>';

                    if(min > parseFloat(results[j].duration.text.slice(0, -5))){
                        min = parseFloat(results[j].duration.text.slice(0, -5));
                        minAddress = originList[i];
                    }


                }
            }
        }
    });
    return longstr;
}

function deleteMarkers(markersArray) {
    for (var i = 0; i < markersArray.length; i++) {
        markersArray[i].setMap(null);
    }
    markersArray = [];

}

js在index.html中可以很好地显示距离和地图。

0 个答案:

没有答案