Я отменял этот код в течение нескольких месяцев, но внезапно не работает.Я пытаюсь загрузить карту и показать на ней некоторые маркеры с позициями базы данных.Ссылка на базу данных и возврат запроса в порядке.
Файл JavaFX:
public class MapController implements Initializable{
private final static Logger LOGGER = Logger.getLogger(FinalizadosController.class.getName());
@FXML
Button changeConductorButton;
@FXML
ComboBox<String> conductorComboBox;
ConductorGestor mConductorGestor = new ConductorGestor();
private List<String> nombreConductoresComboList;
@FXML
WebView mapaWebView;
WebEngine engine;
PosicionGestor mPosicionGestor = new PosicionGestor();
double lat;
double lon;
@FXML
HBox fechaHBox;
private DatePicker fechaDatePicker;
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
fillComboBoxConductor();
fechaDatePicker = new DatePicker(new Locale("es", "ES"));
fechaDatePicker.setDateFormat(new SimpleDateFormat("dd-MM-yyyy"));
fechaDatePicker.getCalendarView().todayButtonTextProperty().set("Today");
fechaDatePicker.getCalendarView().setShowWeeks(false);
fechaDatePicker.getStylesheets().add("/view/DatePicker.css");
fechaHBox.getChildren().add(fechaDatePicker);
final URL urlGoogleMaps = getClass().getResource("googlemapscriptvictor.html");
engine = mapaWebView.getEngine();
lat = 22.209938;
lon = -1.727726;
engine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>() {
public void changed(ObservableValue ov, State oldState, State newState) {
System.out.println("ESTADO CAMBIADO: " + newState);
if (newState == Worker.State.SUCCEEDED) {
mostrarTodosLosConductores();
}
}
});
engine.setJavaScriptEnabled(true);
engine.load(urlGoogleMaps.toExternalForm());
mapaWebView.setOnDragDetected(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent t) {
// intentionally do nothing
}
});
}
protected void mostrarTodosLosConductores() {
try {
LOGGER.log(Level.ERROR, "Inicio mostrarTodosLosConductores() " );
System.out.println("MOSTRAR CONDUCTORES");
for(String condNombre : nombreConductoresComboList) {
LOGGER.log(Level.ERROR, "condNombre: " + condNombre);
Posicion p = mPosicionGestor.selectPosition(condNombre);
LOGGER.log(Level.ERROR, "p: " + p.getIdPosicion());
if(null!=p){
if(p.getIdPosicion()!=0){
if((p.getxPos()!=0)&&(p.getyPos()!=0)){
engine.executeScript("addInfoBulle('"+ condNombre +"',"+p.getxPos()+","+p.getyPos()+",'"+p.getmFecha()+"','"+"direccion"+"');");
}
}
}
}
engine.executeScript("goToLocation("+lat+","+lon+");");
} catch (Exception e) {
LOGGER.log(Level.ERROR, UtilsVictor.exceptionStacktraceToString(e));
UtilsVictor.showAvisoScreen("ERROR", e);
}
}
public String getLocationInfo( double lat, double lng) {
JSONObject jsonObject = new JSONObject();
String json = new String();
try {
json = readUrl("http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat + ","+lng + "&sensor=true_or_false" );
jsonObject = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject location;
String location_string = new String();
try {
//Get JSON Array called "results" and then get the 0th complete object as JSON
location = jsonObject.getJSONArray("results").getJSONObject(0);
// Get the value of the attribute whose name is "formatted_string"
location_string = location.getString("formatted_address");
} catch (JSONException e1) {
e1.printStackTrace();
}
return location_string;
}
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
}
файл thml, ключ вставлен нормально, в моем коде здесь вставлено xxxx
<!DOCTYPE html>
<html>
<head>
<title>Java-Buddy: Google Maps</title>
<script src="http://maps.google.com/maps/api/js?key=xxxx"></script>
<style>
#mapcanvas {
height: 600px;
width: 100%
}
</style>
</head>
<body>
<h1>Mapa Situación Chóferes</h1>
<div id="mapcanvas">
<script type="text/javascript">
document.map = new google.maps.Map(document
.getElementById("mapcanvas"));
var latlng = new google.maps.LatLng(41.78266856772762, -1.976816946635381);
var Options = {
zoom : 9,
center : latlng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
//creamos el mapa
var map = new google.maps.Map(document.getElementById("mapcanvas"),
Options);
var arrayPuntosRuta = [];
var markersArray = [];
function borrarPuntos(){
arrayPuntosRuta = [];
}
function addPosicionARuta(x,y) {
var puntoRuta = new google.maps.LatLng(x,y);
arrayPuntosRuta.push(puntoRuta);
}
function showRuta(puntosRuta) {
var flightPath = new google.maps.Polyline({
path : arrayPuntosRuta,
geodesic : true,
strokeColor : '#FF0000',
strokeOpacity : 1.0,
strokeWeight : 2
});
flightPath.setMap(map);
}
//Creamos el marker que se va a ir mostrando
function addInfoBulle(nombreconductor, x, y, hora, direccion) {
var marker = new google.maps.Marker({
position : new google.maps.LatLng(x, y),
map : map,
draggable : false,
//icon: carMarkerImage,
title : "tit",
autoPan : true
});
var contentString = '<div id="content"><p>Conductor: <strong>'
+ nombreconductor
+ '</strong></p> <p> Hora: <strong>'
+ hora
+ '</strong></p><p>Dirección:<strong>' + direccion + '</strong></p><p>Velocidad:<strong>Km</strong></p></div>';
var infobulle = new google.maps.InfoWindow({
content : contentString
});
markersArray.push(infobulle);
google.maps.event.addListener(marker, 'mouseover', function() {
infobulle.open(map, marker);
});
}
function goToLocation(x, y) {
alert("goToLocation, x: " + x + ", y:" + y);
var latLng = new google.maps.LatLng(x, y);
map.setCenter(latLng);
}
</script>
</div>
</body>
</html>
И провал:
[INFO] 2018-11-21 21:23:24,555 - controller.FinalizadosController -90966 [JavaFX Application Thread] ERROR controller.FinalizadosController - netscape.javascript.JSException: TypeError: 'undefined' is not an object
at com.sun.webpane.platform.WebPage.twkExecuteScript(Native Method)
at com.sun.webpane.platform.WebPage.executeScript(Unknown Source)
at javafx.scene.web.WebEngine.executeScript(Unknown Source)
at controller.MapController.mostrarTodosLosConductores(MapController.java:162)
at controller.MapController$1.changed(MapController.java:128)
at controller.MapController$1.changed(MapController.java:1)
at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(Unknown Source)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(Unknown Source)
at javafx.beans.property.ReadOnlyObjectWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(Unknown Source)
at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(Unknown Source)
at javafx.beans.property.ObjectPropertyBase.markInvalid(Unknown Source)
at javafx.beans.property.ObjectPropertyBase.set(Unknown Source)
at javafx.scene.web.WebEngine$LoadWorker.updateState(Unknown Source)
at javafx.scene.web.WebEngine$LoadWorker.dispatchLoadEvent(Unknown Source)
at javafx.scene.web.WebEngine$LoadWorker.access$600(Unknown Source)
at javafx.scene.web.WebEngine$PageLoadListener.dispatchLoadEvent(Unknown Source)
at com.sun.webpane.platform.WebPage.fireLoadEvent(Unknown Source)
at com.sun.webpane.platform.WebPage.fwkFireLoadEvent(Unknown Source)
at com.sun.webpane.webkit.network.URLLoader.twkDidFinishLoading(Native Method)
at com.sun.webpane.webkit.network.URLLoader.access$1300(Unknown Source)
at com.sun.webpane.webkit.network.URLLoader$6.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(Unknown Source)
at com.sun.glass.ui.win.WinApplication$3$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Почему это происходит?и вдруг ...
Спасибо всем за помощь!