Search code examples
google-mapsgoogle-maps-api-3javafx-webengine

Adding multiple markers in google map from javaFX application by executing webengine.executescript method


I am trying to add multiple markers from my javaFX application through the webengine.executescript() method .I have fallen the method in a loop to show all the markers but it just shows the last positioned marker .Here is my javaFx code for that

 Button refresh = new Button("Refresh");
        refresh.setOnAction(new EventHandler<ActionEvent>() {
                                @Override
                                public void handle(ActionEvent arg0) {

                                    String[] latitude = {"23.806744","10"};
                                    String[] longitude = {"90.3685549","20"};
                                    //networking should be here

                                    for (int i = 0; i < latitude.length; i++) {
                                        lat = Double.parseDouble(latitude[i]);
                                        lon = Double.parseDouble(longitude[i]);

                                        System.out.printf("%.2f %.2f%n", lat, lon);

                                        webEngine.executeScript("" +
                                                        "window.lat = " + lat + ";" +
                                                        "window.lon = " + lon + ";" +
                                                        "document.goToLocation(window.lat,window. lon);"
                                        );
                                    }
                                }
                            }
        );

function initMap() {


  var latlng = new google.maps.LatLng(35.857908, 10.598997);

  var origin_place_id = null;
  var destination_place_id = null;
  var travel_mode = google.maps.TravelMode.DRIVING;
  var map = new google.maps.Map(document.getElementById('map'), {
    mapTypeControl: false,
    center: {lat: -33.8688, lng: 151.2195},
    zoom: 13
  });


  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer;
  directionsDisplay.setMap(map);

  var origin_input = document.getElementById('origin-input');
  var destination_input = document.getElementById('destination-input');
  var modes = document.getElementById('mode-selector');

  map.controls[google.maps.ControlPosition.TOP_LEFT].push(origin_input);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(destination_input);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(modes);

  var origin_autocomplete = new google.maps.places.Autocomplete(origin_input);
  origin_autocomplete.bindTo('bounds', map);
  var destination_autocomplete =
      new google.maps.places.Autocomplete(destination_input);
  destination_autocomplete.bindTo('bounds', map);



  function expandViewportToFitPlace(map, place) {
    if (place.geometry.viewport) {
      map.fitBounds(place.geometry.viewport);
    } else {
      map.setCenter(place.geometry.location);
      map.setZoom(17);
    }
  }

  origin_autocomplete.addListener('place_changed', function() {
    var place = origin_autocomplete.getPlace();
    if (!place.geometry) {
      window.alert("Autocomplete's returned place contains no geometry");
      return;
    }
    expandViewportToFitPlace(map, place);

    // If the place has a geometry, store its place ID and route if we have
    // the other place ID
    origin_place_id = place.place_id;
    route(origin_place_id, destination_place_id, travel_mode,
          directionsService, directionsDisplay);
  });

  destination_autocomplete.addListener('place_changed', function() {
    var place = destination_autocomplete.getPlace();
    if (!place.geometry) {
      window.alert("Autocomplete's returned place contains no geometry");
      return;
    }
    expandViewportToFitPlace(map, place);

    // If the place has a geometry, store its place ID and route if we have
    // the other place ID
    destination_place_id = place.place_id;
    route(origin_place_id, destination_place_id, travel_mode,
          directionsService, directionsDisplay);
  });

  function route(origin_place_id, destination_place_id, travel_mode,
                 directionsService, directionsDisplay) {
    if (!origin_place_id || !destination_place_id) {
      return;
    }



    directionsService.route({
          origin: {'placeId': origin_place_id},
          destination: {'placeId': destination_place_id},
          provideRouteAlternatives: true,
          travelMode: google.maps.DirectionsTravelMode.DRIVING
    }, function(response, status) {
      if (status === google.maps.DirectionsStatus.OK) {
      for (var i = 0, len = response.routes.length; i < len; i++) {
            new google.maps.DirectionsRenderer({
                    map: map,
                    directions: response,
                    routeIndex: i
                });


            }

      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });

}
     var marker = new google.maps.Marker({
            position: new google.maps.LatLng(0,0),
            map: map,
            draggable: false,
            title: "",
            autoPan: false

        });


    document.goToLocation = function(x, y) {
       alert("goToLocation, x: " + x +", y:" + y);
       var latlng = new google.maps.LatLng(x, y);
       marker.setPosition(latlng);
       //map.setCenter(latLng);
    }

}
    
<!DOCTYPE html>
<html>
  <head>
    <title>Place Autocomplete</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
        width:100%;
      }
.controls {
  margin-top: 15px;
  border: 1px solid transparent;
  border-radius: 2px 0 0 2px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  height: 32px;
  outline: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

#origin-input,
#destination-input {
  background-color: #fff;
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
  margin-left: 12px;
  padding: 0 11px 0 13px;
  text-overflow: ellipsis;
  width: 200px;
}

#origin-input:focus,
#destination-input:focus {
  border-color: #4d90fe;
}

#mode-selector {
  color: #fff;
  background-color: #4d90fe;
  margin-left: 12px;
  padding: 5px 11px 0px 11px;
}

#mode-selector label {
  font-family: Roboto;
  font-size: 13px;
  font-weight: 300;
}


    </style>
  </head>
  <body>
    <input id="origin-input" class="controls" type="text"
        placeholder="Enter an origin location">

    <input id="destination-input" class="controls" type="text"
        placeholder="Enter a destination location">



    <div id="map"></div>

 

It would be nice if anyone could help


Solution

  • Your problem is you create your marker only once. You then call document.goToLocation in your loop, simply updating the position of that one marker every time. At the end of the loop, it has the position of the last of those locations.

    If you want a marker on every location, create a marker inside the document.goToLocation function:

    document.goToLocation = function(x, y) {
       alert("goToLocation, x: " + x +", y:" + y);
    
       var marker = new google.maps.Marker({
            position: new google.maps.LatLng(x, y),
            map: map,
            draggable: false,
            title: "",
            autoPan: false
        });
    }