I have the following code in javascript:
<script type="text/javascript"
src="#{facesContext.externalContext.requestContextPath}/js/sample-points.js"></script>
<script type="text/javascript">//<![CDATA[
var cloudmade = new CM.Tiles.CloudMade.Web({key: 'bbb'});
var map = new CM.Map('cm-example', cloudmade);
map.setCenter(new CM.LatLng(51.50874, 22.76367), 4);
var markers = [];
for (var i = 0; i < samplePoints.length; i++) {
markers.push(new CM.Marker(new CM.LatLng(samplePoints[i][0], samplePoints[i][1])));
}
var clusterer = new CM.MarkerClusterer(map, {clusterRadius: 70});
clusterer.addMarkers(markers);
//]]></script>
"samplePoints" is an array of coordinates which I can use to show markers on the map.
Map is showing here:
<div id="cm-example" style="width: 99.5%; height: 600px"></div>
How can I provide this array from jsf/richfaces without using file (e.g. I want to fetch those data from db, create array and send to this script)?
Thanks
Just let JSF print it as if it is JavaScript code.
Replace
var markers = [];
for (var i = 0; i < samplePoints.length; i++) {
markers.push(new CM.Marker(new CM.LatLng(samplePoints[i][0], samplePoints[i][1])));
}
by (assuming Facelets)
var markers = [];
<ui:repeat value="#{bean.samplePoints}" var="samplePoint">
markers.push(new CM.Marker(new CM.LatLng(#{samplePoint[0]}, #{samplePoint[1]})));
</ui:repeat>
where #{bean.samplePoints} returns a List<BigDecimal[]> or something.
See this Link
using jsFunction you can load any data structure (e.g. Points), and on your clients side you get a javaScript data structure that you can easily access it (point.x).
Related
I'm making an app with GoogleMap inside DJ Native webBrowser component. I load page as a string using webBrowser.setHTMLContent(String). HTML file contains JavaScript which add markers to map.
I made simple html file with google-maps-api functions.
It works perfect on Chrome as well as Firefox. But not in webBrowser (djnative).
I discovered that script without new marker statement(google.maps.Marker) works OK.
Have anyone got any idea what's wrong?
Is there any way to show console log from webBrowser (like ctrl+shift+J in Chrome)
This is script code:
<script type="text/javascript" src=https://maps.googleapis.com/maps/api/js?key=[MY_KEY]&sensor=false">
</script>
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.236302, 21.007636),
zoom: 10
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var t = [];
var x = [];
var y = [];
var h = [];
t.push('Location Name 1');
x.push(52.232097);
y.push(20.927985);
h.push('<p><strong>Location Name 1</strong><br/>Address 1</p>');
t.push('Location Name 2');
x.push(52.245097);
y.push(20.945985);
h.push('<p><strong>Location Name 2</strong><br/>Address 2</p>');
/*this is error making code*/
var i = 0;
for ( item in t ) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(x[i], y[i]),
map: map,
title: t[i],
});
i++;
} /*this is end of error making code*/
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
1.Dj is using ie as default. did you try opening the html with ie?
2.In dj, you can not always setting the content and expect it run. for example, the tinymce editor, does not run if you set the editor.html (html containint tinymce) directly. That is why the author of dj made internal webserver for editors. You have to call it through an address (for editor ck and tinymce, dj calls localhost, http://127.0.0.1/tinymce/.. but the structure is too complex to be detailed here. you may try for testing purpose, putting your html to a simple web page (tomcat) and call it through loadURL (instead of setContent)
I am able to have the response from a servlet and also able to show it on jsp page, but if I try to populate the same in a drop down, i am not able to-
Servlet code
String sql = "SELECT records from department";
ResultSet rs = s.executeQuery(sql);
Map<String, String> options = new LinkedHashMap<String, String>();
while (rs.next()) {
options.put(rs.getString("records"),rs.getString("records"));
}
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
JSP code---
JS code
<script type="text/javascript">
$(document).ready(function () { // When the HTML DOM is ready loading, then execute the following function...
$('.btn-click').click(function () { // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
$.get('/testservlet', function (responseJson) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
//alert(responseJson);
var $select = $('#maindiv'); // Locate HTML DOM element with ID "someselect".
$select.find('option').remove(); // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
$.each(responseJson, function (key, value) { // Iterate over the JSON object.
$('<option>').val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
});
});
});
});
</script>
HTML Code--
<input type="button" class="btn-click" id="best" value="check"/>
<div id="maindiv" style="display: block"></div>
If I create a <ul> and <li> I can have the data from the response on my page but not able to create the select options? Any help on this would be great.
Try it again after removing beginning /.
$.get('testservlet', function (responseJson)
The JSON string is not in proper way. It should be something like this. Why are you using JSON string here whereas you are passing only records as key as well as value.
Simply return a comma separated string from Servlet and split it jQuery.
Find example here for Iterating a comma separated string
Sample code:
var items = responseJson.split(',');
for ( var i = 0; i < items.length; i++) {
$('<option>').val(items[i]).text(items[i]).appendTo($select);
}
I am trying to load a table with data by initializing a Javascript variable with a string in JSON format. If I declare:
<script type="text/javascript">
var data = new String("{totalCount: '1', identifier: 'EntityID', items: [{'EntityID':'1','Country':'United States','Region':'','State':'California','County':'Santa Clara','City':'San Jose','ZipCode':'95134'}]}");
var d3 = eval('(' + data + ')');
<span dojoType="dojo.data.ItemFileWriteStore" jsId="dataStore" data=d3></span>
</script>
then my table will correctly load the row.
I have tried initializing a Java string before my script and then passing that object into a Javascript variable like so:
<%
String d = "{totalCount: '1', identifier: 'EntityID', items: [{'EntityID':'1','Country':'United States','Region':'','State':'California','County':'Santa Clara','City':'San Jose','ZipCode':'95134'}]}";
%>
<script type="text/javascript">
var data = new String(<%=d%>);
// var data = new String(d) // tried this as well
var d3 = eval('(' + data + ')');
<span dojoType="dojo.data.ItemFileWriteStore" jsId="dataStore" data=d3></span>
</script>
My table does not recognize this and is unable to load the row when I attempt to pass it this way. How can I properly pass a Java string to Javascript so that my table will be able to load the data?
Try with quotes around.
var data = new String("<%= d %>");
I am new to Java Script. I am using it, in combination with Java Server Faces 2.0.
I want to add some points to define a Polilyne using GoogleMaps Apiv3. My problem is that I can't add a FOR statement to the javascript, because it dumps. If I comment this FOR loop, it also dumps. The dump I am getting is: "javax.servlet.ServletException: null source".
Has anyone any suggestion to solve this? Thanks in advance, Emanuel
<script type="text/javascript">
function initialize()
{
var longit = "${dateRange.longitude}" ;
var lat = "${dateRange.latitude}" ;
var latlng = new google.maps.LatLng(lat, longit);
var myOptions =
{
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var points = [];
var cadena1 = "${dateRange.latArray}" ;
var cadena2 = "${dateRange.longArray}" ;
var latArray = cadena1.split('?');
var longArray = cadena2.split('?');
/* The code Below is the one that fails */
for (var i=0; i < latArray.length; i++)
{
points.push(new google.maps.LatLng(latArray[i], longArray[i]));
}
/* Finish of the error code */
// The Polilyne is created
var mapPath = new google.maps.Polyline
({
path: points,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 4
});
mapPath.setMap(map);
}
</script>
</head>
<body onload="initialize()">
<h:graphicImage url="http://localhost:8080/gps_tracking/faces/resources/images/logo.jpg">
</h:graphicImage>
<h1 align="center">Sol-Tech</h1><br />
<hr></hr>
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
Questions:
Hi,
I want to embed a dynamic google map in my website by IP address. I got the lat/long data using IPlocation tools. I could not yet connect the lat/log data from IPlocation to google map java codes. I m not sure how to format/define/put latitude and longitude in load map function. here are things I tried and did not work yet:
I tried , into javascript code,
I also tried manually putting values for $latitude and $longitude.
I tried directly putting 'ip2location_latitude()' and 'ip2location_longitude()' in java codes.
eventually I need to get a location history based on IP and record the location data to a database.
Thanks in advance
here is the summary of my code:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <!-- Google map API v3 -->
<?php
$latitude = 'ip2location_latitude()'; //------------ IP latitude
$longitude = 'ip2location_longitude()'; //------------ IP latitude ip2location_longitude()
?>
<!-- Start loading canvas google map -->
<script type="text/javascript">
function loadmap () {
var latlng = new google.maps.LatLng($latitude,$longitude);
var option = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), option);
createMarker(latitude,logitude, 'lol');
downloadUrl("airport.xml", function(data) {
var xml = xmlParse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
document.getElementById("test").innerHTML = markers.length;
for (var i = 0; i < markers.length; i++) {
var info = markers[i].getAttribute("info");
var lat = parseFloat(markers[i].getAttribute("lat"));
var lon = parseFloat(markers[i].getAttribute("lng"));
createMarker(lat, lon, info);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function createMarker(lat, lon, info){
var myLatlng = new google.maps.LatLng($latitude,$longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"My location",
icon: "http://google-maps-icons.googlecode.com/files/airport.png"
});
}
</script>
<!-- End Geting map via latitude and longitude-->
<!-- Start calling load map function to load the map -->
<body onload="loadmap ()">
<div id="map_canvas" style="width:400px; height:300px"></div>
<div id="test" style="width:50%; height:50%"></div>
<!-- End calling load map function to load the map -->
You forgot to use echo/print to print the values of the PHP-variables.
Inside createMarker you should refer to the provided arguments(lat,lon) instead of $latitude/$longitude
Fixed version:
<body onload="loadmap ()">
<script src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script src="http://www.iplocationtools.com/iplocationtools.js?key=YOURKEY">
</script>
<?php
$latitude = 'ip2location_latitude()'; //------------ IP latitude
$longitude = 'ip2location_longitude()'; //------------ IP latitude ip2location_longitude()
?>
<script type="text/javascript">
function loadmap () {
var latlng = new google.maps.LatLng(<?php echo $latitude;?>,<?php echo $longitude;?>);
var option = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), option);
createMarker(<?php echo $latitude;?>,<?php echo $longitude;?>, 'lol');
}
function createMarker(lat, lon, info){
var myLatlng = new google.maps.LatLng(lat,lon);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"My location",
icon: "http://google-maps-icons.googlecode.com/files/airport.png"
});
}
</script>
<div id="map_canvas" style="width:400px; height:300px"></div>
<div id="test" style="width:50%; height:50%"></div>
</body>
But however, this service isn't very accurate, for me it shows a location 400km away from my current place. I would suggest to use browser-implemented geolocation.