我一直在尝试生成带有纬度和经度的 map ,我从 MYSQL DB 获取这些纬度和经度。 我有一个 java 类,它将连接到数据库并检索纬度、经度,因此我需要将这些值传递给具有生成 map 的代码的 JavaScript。
在Java脚本中,我有一个名为addmarker()的函数,它有纬度和经度。实际要求是我必须将纬度,经度从java类传递给Java脚本。
这是我的java代码:
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "db5";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
pst = conn.prepareStatement("select latitude,longitude from nidgis where nidevid=?");
pst.setString(1, n);
rs = pst.executeQuery();
while(rs.next())
{
rs.getInt("latitude");
rs.getInt("longitude");
}
}
catch (Exception e)
{
System.out.println(e);
}
这是我的 JS 代码:
<script>
function addMarker()
{
var vehicle = new MQA.Poi({
lat: vehicle_lat,
lng: vehicle_lng,
});
var icon = new MQA.Icon(
'https://cdn2.iconfinder.com/data/icons/gpsmapicons /blue/gpsmapicons07.png',
35, 42);
vehicle.setIcon(icon);
vehicle.setKey("abc");
map.addShape(vehicle);
vehicle.setRolloverContent("Vehicle # KA05 9999");
}
MQA.EventUtil.observe(window, 'load', function() {
/*Create an object for options*/
var options={
elt:document.getElementById('map'), /*ID of element on the page where you want the map added*/
zoom:10, /*initial zoom level of map*/
latLng:{lat:39.743943, lng:-105.020089}, /*center of map in latitude/longitude*/
mtype:'map' /*map type (map)*/
};
/*Construct an instance of MQA.TileMap with the options object*/
window.map = new MQA.TileMap(options);
MQA.withModule('geocoder', function() {
/*Executes a geocode and adds result to the map*/
map.geocodeAndAddLocations("Denver CO");
});
});
</script>
<body>
<div id='map' style='width:1560px; height:730px;'></div>
<button id="getBasicSample" onclick="addMarker();">show veh1</button>
</body>
最佳答案
您的 Java 代码应该位于 servlet 中,然后您应该将 lat/lng
结果添加到容器中并序列化为 JSON,例如 GSON :
class Result {
double lat;
double lng;
Result(double l, double ll) {
this.lat = l;
this.lng = ll;
}
}
List<Result> results = new ArrayList<>();
while (rs.next()) {
results.add(new Result(rs.getInt("latitude"), rs.getInt("longitude")));
}
final TypeToken<List<Result>> resultsType = new TypeToken<List<Result>>() {};
response.getWriter().write(new Gson().toJson(results, resultsType.getType()))
然后在您的 javascript 中,假设这是使用 Ajax 调用的,您可以使用 json:
var markers = [];
for (var i = 0; i < responseJSON.length) {
markers.push(responseJSON[i].lat + ', ' + responseJSON[i].lng)
}
关于java - 如何将变量从java类传递到Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28164843/