Google map don't recognize double - javascript

I want to create a map from the values I get from my database using this tutorial.
I'm sure that the values in my jsp are double, but they are not shown in my map (it appears grey).
This is my jsp:
<c:if test="${tei.getLatitudine() != null}">
<span class="elemento">latitudine:</span>
<div id="latitudine">${tei.getLatitudine()}</div>
<br/></c:if>
<c:if test="${tei.getLongitudine() != null}">
<span class="elemento">longitudine:</span>
<div id="longitudine">${tei.getLongitudine()}</div>
<br/></c:if>
I'm trying differents approach:
function initMap() {
var latitudine = $("#latitudine").val;
var longitudine = $("#longitudine").val;
var uluru = {lat: latitudine, lng: longitudine};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
or:
function initMap() {
var latitudine = '${tei.getLatitudine()}';
var longitudine = '${tei.getLongitudine()}';
var uluru = {lat: latitudine, lng: longitudine};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
None of the two or other forms I'm using it works.
Thanks in advance for any help.
EDIT1:
The error in my console is:
InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number _.kb # js?key=AIzaSyCIVrSpAqIBx532NG59pY4biIuc5xQGgtA&callback=init‌​Map:37 js?key=AIzaSyCIVrSpAqIBx532NG59pY4biIuc5xQGgtA&callback=init‌​Map:37
InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number _.kb # js?key=AIzaSyCIVrSpAqIBx532NG59pY4biIuc5xQGgtA&callback=init‌​Map:37
but if I write in my jsp:
${tei.getLongitudine().getClass()}
it returns class double.
EDIT2:
If I wrote in my js:
var latitudine = ${tei.longitudine}
I get this error:
message: "initMap is not a function"
name: "InvalidValueError"
stack: "Error
at new Eb (https://maps.googleapis.com/maps/api/js?key=mykey(hidden4privacy)&callback=initMap:41:365)
at Object._.Fb (https://maps.googleapis.com/maps/api/js?key=mykey(hidden4privacy)&callback=initMap:41:475)
at Og (https://maps.googleapis.com/maps/api/js?key=mykey(hidden4privacy)&callback=initMap:96:420)
at https://maps.googleapis.com/maps/api/js?key=mykey(hidden4privacy)&callback=initMap:131:58
at Object.google.maps.Load (https://maps.googleapis.com/maps/api/js?key=mykey(hidden4privacy)&callback=initMap:21:5)
at https://maps.googleapis.com/maps/api/js?key=mykey(hidden4privacy)&callback=initMap:130:20
at https://maps.googleapis.com/maps/api/js?key=mykey(hidden4privacy)&callback=initMap:131:73"

If you have model like this;
public class MyModel{
private double longitudine;
public double getLongitudine() {
return longitudine;
}
public void setLongitudine(double longitudine) {
this.longitudine = longitudine;
}
}
and put request or session your model
MyModel d = new MyModel();
d.setLongitudine(24);
session.setAttribute("lng",d); // or
// request.setAttribute("lng",d);
then you can access properties using EL in JS like this.
function myFunction() {
var a = ${sessionScope.lng.longitudine}; /*or*/
/* var a = ${requestScope.lng.longitudine}; */
var b = a + 5;
console.log(b);
}

Related

How to put List in viewbag data to javascript API marker in view?

I have a list called Geolocations which contains latitudes and longitudes.
List<Geolocation> AllGeoLocations = new List<Geolocation>();
Geolocation Class:
public class Geolocation
{
public string Latitude { get; set; }
public string Longitude{ get; set; }
}
I am sending this list in ViewBag from controller to view.
Viewbag : ViewBag.GeoList = AllGeoLocations;
In view under script, In markers array, within coords:{ } I want to put the latitude and longitude values send from the controller with Viewbag.
<script>
var map;
var src = 'https://s3-ap-southeast-1.amazonaws.com/cloudcreativeltd/Rail_Ex_RoW_my.kml';
function initMap() {
// Map options
var options = {
zoom: 12,
center: { lat: 23.6850, lng: 90.3563 }
}
// New map
var map = new google.maps.Map(document.getElementById('map'), options);
// Array of markers
var markers = [
{
coords: { lat: , lng: },
content: '<h1></h1>'
}
];
</script>
Try the following approach, this might be help you. Note : I have not tested this code (not executed)
< script >
var map;
var src = 'https://s3-ap-southeast-1.amazonaws.com/cloudcreativeltd/Rail_Ex_RoW_my.kml';
function initMap() {
// Map options
var options = {
zoom: 12,
center: {
lat: 23.6850,
lng: 90.3563
}
}
// New map
var map = new google.maps.Map(document.getElementById('map'), options);
// Array of markers
var geoArray = #Html.Raw(Json.Encode(#ViewBag.GeoList));
for (var i = 0; i < geoArray.length; i++) {
var myLatLng = new google.maps.LatLng(geoArray[i].Latitude, geoArray[i].Longitude);
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
}
}

trying to dinamically load data points to a google heat map layer

I am trying to add to a google map a heat-map layer populated with data points from an SQL back-end. So far I managed to display the map and I do call a code behind method that return an arrays of JSON latitude and longitude points.
When I try to add the points to the heat-map nothing is displayed and I do not get any server or client side errors. below I pasted a snippet of the JSON I am passing to the java script function that should populate the heat-map layer, the html mark-up and the java script code.
The final result should be the heat-map layer displaying over the map. Currently only the map is displaying.
the "alert(data);" is displaying but the "alert(jsonData);" is not displaying
from c# I am using JSON.NET to serialize the data.
[{"CoordinatesObject":[{"Latitude":57.149605,"Longitude":-2.096916}]},{"CoordinatesObject":[{"Latitude":57.14871,"Longitude":-2.097806}]},{"CoordinatesObject":[{"Latitude":57.14905,"Longitude":-2.097004}]}]
<div class="row">
<div class="col-12 align-content-md-center">
<div id="floating-panel" class="floating-panel">
<button onclick="toggleHeatmap()">Toggle Heatmap</button>
<button onclick="changeGradient()">Change gradient</button>
<button onclick="changeRadius()">Change radius</button>
<button onclick="changeOpacity()">Change opacity</button>
</div>
<div id="map" class="map"> </div>
</div>
</div>
var map, heatmap;
function initMap() {
var CenterLat = 55.95206;
var CenterLong = -3.19648;
var mapCoordinates = {
center: new google.maps.LatLng(CenterLat, CenterLong),
zoom: 8,
mapTypeId: 'roadmap'
}
map = new google.maps.Map(document.getElementById('map'), mapCoordinates);
heatmap = new google.maps.visualization.HeatmapLayer({
data: getPoints(),
map: map
});
}//end InitMap
function getPoints() {
var Json =<%=GetJsonData()%>;
//var jsonData = JSON.parse(Json);
for (var i = 0; i < Json.length; i++) {
var LatLongObj = Json.CoordinatesObject[i];
//ArrLatLong.push("location:" + new google.maps.LatLng(LatLongObj.Latitude, LatLongObj.Longitude));
var marker = new google.maps.Marker({
'location': new google.maps.LatLng(LatLongObj.Latitude, LatLongObj.Longitude),
'map': map,
'weight': i
});
}
}
please note that this is the first time I am playing with google map API.
EDIT:
my working solution
var map, heatmap;
function initMap() {
var CenterLat = 56.816918399;
var CenterLong = -4.1826492694;
var ArrMarkers=[];
var ServerData =<%=GetJsonData()%>;
var Latitude ;
var Longitude;
for (var i = 0; i < ServerData.length; i++) {
Latitude = ServerData[i].Latitude;
Longitude = ServerData[i].Longitude;
var marker = { location: new google.maps.LatLng(Latitude, Longitude) };
ArrMarkers.push(marker);
}
var mapCoordinates = {
center: new google.maps.LatLng(CenterLat, CenterLong),
zoom: 7,
mapTypeId: 'roadmap'
};
map = new google.maps.Map(document.getElementById('map'), mapCoordinates);
heatmap = new google.maps.visualization.HeatmapLayer({
data: ArrMarkers,
radius: 15,
opacity:0.5,
map: map
});
}//end InitMap
FInal soultion
var map, heatmap;
function initMap() {
var CenterLat = 56.816918399;
var CenterLong = -4.1826492694;
var ArrMarkers=[];
var ServerData =<%=GetJsonData()%>;
var Latitude ;
var Longitude;
for (var i = 0; i < ServerData.length; i++) {
Latitude = ServerData[i].Latitude;
Longitude = ServerData[i].Longitude;
var marker = { location: new google.maps.LatLng(Latitude, Longitude) };
ArrMarkers.push(marker);
}
var mapCoordinates = {
center: new google.maps.LatLng(CenterLat, CenterLong),
zoom: 7,
mapTypeId: 'roadmap'
};
map = new google.maps.Map(document.getElementById('map'), mapCoordinates);
heatmap = new google.maps.visualization.HeatmapLayer({
data: ArrMarkers,
radius: 15,
opacity:0.5,
map: map
});
}//end InitMap

Try to create a cluster unsing a sample but addLayer got undefined

Here API clustering error: "addLayer is not defined"
Error I am calling the function startClustering, but I get a error map.addLayer is undefined.
I think maybe the map object lost the context scope, but how can I could pass the right scope to have access to addLayer function from the map.
//Boilerplate map initialization code starts below:
var defaultLayers = platform.createDefaultLayers();
var map = new H.Map(document.getElementById('map'),
defaultLayers.normal.map, {
center: {
lat: -19.9211375,
lng: -43.9490617,
},
zoom: 6
});
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// create default UI with layers provided by the platform
var ui = H.ui.UI.createDefault(map, defaultLayers, 'pt-BR');
function startClustering(map, data) {
var dataPoints = data.map(function (item) {
return new H.clustering.DataPoint(item.coords.lat, item.coords.lng);
});
var clusteredDataProvider = new H.clustering.Provider(dataPoints, {
clusteringOptions: {
eps: 32,
minWeight: 2
}
});
var clusteringLayer = new H.map.layer.ObjectLayer(clusteredDataProvider);
map.addLayer(clusteringLayer);
}
startClustering(map, travelData);
I was not able to reproduce the "addLayer is not defined" error you observed. Since you did not provide a full listing (for example, travelData is not defined), I suspect the issue may not be demonstrated in the code sample to help you debug.
It looks like you followed the clustering example from the documentation:
https://developer.here.com/api-explorer/maps-js/v3.0/clustering/marker-clustering
There is no need to wrap it in a function though if you suspect a scoping issue. For example this works for me:
var platform = new H.service.Platform({
'app_id': 'your-app-id',
'app_code': 'your-app-code',
});
var defaultLayers = platform.createDefaultLayers();
var map = new H.Map(
document.getElementById('map'),
defaultLayers.normal.map, {
center: {lat: -19.9211375,
lng: -43.9490617},
zoom: 6,
});
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
var ui = H.ui.UI.createDefault(map, defaultLayers, 'pt-BR');
var travelData = [
{lat: -19.8211, lng: -43.9490617},
{lat: -19.7211, lng: -43.9490617},
{lat: -19.6211, lng: -43.9490617},
{lat: -19.5211, lng: -43.9490617},
{lat: -19.4211, lng: -43.9490617},
{lat: -19.3211, lng: -43.9490617},
];
var dataPoints = travelData.map(function(item) {
return new H.clustering.DataPoint(item.lat, item.lng);
});
var clusteredDataProvider = new H.clustering.Provider(dataPoints, {
clusteringOptions: {eps: 32, minWeight: 2 }
});
var clusteringLayer = new H.map.layer.ObjectLayer(clusteredDataProvider);
map.addLayer(clusteringLayer);
It's not exactly the same as I simplified travelData a bit so it may depend on your dataset. Also make sure you are including the mapjs-clustering.js script in your HTML, though you'd see an error like "H.clustering is undefined" if that were the issue.

How can I use JavaScript in Razor for google maps API

I am trying to use a 'foreach' loop to place a series of markers on the map using coordinates from a database. The retrieval of the data is not an issue so for now I'm not bothered about the map showing the correct locations. The issue is that when inside the 'foreach' loop, any code for the marker placement is immediately passed over. Any ideas?
Here is the current code:
<script>
function myMap() {
var lat = 52.4283381;
var lng = -1.601519;
var myLatLng = { lat: 52.428381, lng: -1.601519 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(lat, lng)
});
}
</script>
<script>
#foreach (var mapVars in ViewData.Model)
{
<text>
var marker = new google.maps.Marker
({
position: new google.maps.LatLng (52.428381 , -1.601519),
map: map,
title: "" + i,
});
</text>
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBfvqLwEOTU3oFoiJOmmloYJFYUA801lF8&callback=myMap"></script>
Try serialize your ViewData.Model to a javascript object and than loop from there.
Something like this:
<script>
function myMap() {
var lat = 52.4283381;
var lng = -1.601519;
var myLatLng = { lat: 52.428381, lng: -1.601519 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(lat, lng)
});
}
</script>
<script>
window.data = #(Html.Raw(js.Serialize(ViewData.Model)));
var markers = [];
for(i = 0; i < window.data.length; i++)
{
markers.push(new google.maps.Marker
({
position: new google.maps.LatLng (52.428381 , -1.601519),
map: map,
title: "" + i,
}));
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBfvqLwEOTU3oFoiJOmmloYJFYUA801lF8&callback=myMap"></script>

Razor with javascript issue

I created a google map and I want to add a list of markers on it. But I have some razor-javascript issues.
My cshtml file has a model #model IEnumerable<MCN.Domain.Entities.Location>
My model loading is fine it contains all values.
I debug JS code in browser and it gets in addMarker method but stop at var marker = new google.maps.Marker({ part.
In visual studio I have green underline on #foreach (var item in Model) { with message: "Conditional compilation is turned off"
This is JS part:
<script type="text/javascript">
(function () {
window.onload = function () {
var mapDiv = document.getElementById('map');
var latlng = new google.maps.LatLng('41.01146', '24.921659');
var options = { styles: styleArray,
center: latlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(mapDiv, options);
#foreach (var item in Model) {
#:addMarker(#item.Latitude, #item.Longitude, '#item.Name', '#item.DiscoveredBy');
}
}
})();
function addMarker(latitude, longitude, title, description)
{
var markerlatLng = new google.maps.LatLng(latitude, longitude);
var title = 'test';
var description = 'test';
var contentString = 'test';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: latLng,
title: title,
map: map,
draggable: false
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
</script>
JS From browser:
(function () {
window.onload = function () {
var mapDiv = document.getElementById('map');
var latlng = new google.maps.LatLng('44.01146', '20.921659');
var options = { styles: styleArray,
center: latlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(mapDiv, options);
addMarker(20.921659, 44.01146, 'Svetozar markovic', 'user');
addMarker(20.92829, 44.010333, 'Glavna Stanica', 'user');
}
})();
Visual Studio isn't expecting to see Razor markup in a <script> tag. That's OK - hopefully they'll add support for this in the future.
The important thing is that you're not getting javascript errors in your browser.
Try surrounding the code itself with parentheses. This will get rid of the error you're seeing.
Example: #Url.Action("MyAction", new { my_param = "my_value" }))

Categories

Resources