Iam trying to use HERE MAPS API, and i want to get markers from mySQL database, i am using the api like showing in here forume but markers doesnt shown im the map, i ma using this code :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.0/mapsjs-ui.css?dp-version=1542186754" />
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-mapevents.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-clustering.js"></script>
</head>
<body>
<div id="map" style="width: 100%; height: 400px; background: grey" />
<script type="text/javascript" charset="UTF-8" >
/**
* Display clustered markers on a map
*
* Note that the maps clustering module http://js.api.here.com/v3/3.0/mapsjs-clustering.js
* must be loaded to use the Clustering
* #param {H.Map} map A HERE Map instance within the application
* #param {Array.<Object>} data Raw data that contains airports' coordinates
*/
function startClustering(map, data) {
// First we need to create an array of DataPoint objects,
// for the ClusterProvider
var dataPoints = data.map(function (item) {
return new H.clustering.DataPoint(item.latitude, item.longitude);
});
// Create a clustering provider with custom options for clusterizing the input
var clusteredDataProvider = new H.clustering.Provider(dataPoints, {
clusteringOptions: {
// Maximum radius of the neighbourhood
eps: 32,
// minimum weight of points required to form a cluster
minWeight: 2
}
});
// Create a layer tha will consume objects from our clustering provider
var clusteringLayer = new H.map.layer.ObjectLayer(clusteredDataProvider);
// To make objects from clustering provder visible,
// we need to add our layer to the map
map.addLayer(clusteringLayer);
}
/**
* Boilerplate map initialization code starts below:
*/
// Step 1: initialize communication with the platform
var platform = new H.service.Platform({
app_id: 'devportal-demo-20180625',
app_code: '9v2BkviRwi9Ot26kp2IysQ',
useHTTPS: true
});
var pixelRatio = window.devicePixelRatio || 1;
var defaultLayers = platform.createDefaultLayers({
tileSize: pixelRatio === 1 ? 256 : 512,
ppi: pixelRatio === 1 ? undefined : 320
});
// Step 2: initialize a map
var map = new H.Map(document.getElementById('map'), defaultLayers.normal.map, {
center: new H.geo.Point(30.789, 33.790),
zoom: 2,
pixelRatio: pixelRatio
});
// Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Step 4: create the default UI component, for displaying bubbles
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Step 5: request a data about airports's coordinates
var url= 'https://jsondataexemple.com/hereapi/jsondata.json';
$.ajax({
type: 'GET',
dataType: 'json',
url: url,
success: function (data) {
startClustering(map, data);
}
});
</script>
</body>
</html>
the Json file is generated from my database by a php script :
[{"id":2812,"latitude":"33.5706476858027","longitude":"-7.600212045766735"},{"id":2811,"latitude":"33.56960668831451","longitude":"-7.6025319565980904"}]
thanks for helping me
In your json, latitude, longitude seems to be String. they should Float.
you may consider using ParseFloat in JS or change your php script.
after testing chrome debuger i found that the probleme is from my local host, but the code work properly in my online host !.
sorry
Related
Leaflet Map not Visible ....
What I am trying to do is creating a map and add external GeoJSON file I already created through QGIS app using SPH file from http://naturalearthdata.com
somehow my map is not visible there i also tried to use mapbox and google API key with leaflet library and sill having same issue
anyone knows the solution ??
I couldn't add my GeoJSON file in here because it's a huge file
Here is my HTML file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="biewport" content="width=device-width, initial-scale=1" />
<title>GeoJSON</title>
<!-- leflet links -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.3.3/dist/leaflet.js"></script>
</head>
<body>
<div id="map"></div>
<!-- <script src="CA_Bulletin_118_Groundwater_Basins.geojson"></script> -->
<script src="test.geojson"></script>
<!-- script file -->
<script src="js/script.js"></script>
</body>
</html>
My script.js file:
//creating a new map
var map = new L.Map('map').setView([51.505, -0.09], 13);
//create a new Geojason layer and set it up to basins var ....
// var test;
var test = L.tileLayer('basins');
var basinslayer = L.geoJson(basins).addTo(map);
And here is my CSS file:
/*General CSS */
html, body, #map {
height: 100%;
width: 100%;
font-family: sans-serif;
}
#map {
width: 50%;
height: 50%;
}
I'm also importing a geojson file to generate the points on my map. I used the $.getJSON from jquery to import the geojson file, load the data, and create the points.
If you want to try this method, you have to add jQuery in the head of your html, like this (also found here for the latest cdn):
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
My $.getJSON looks like this:
var getjson = $.getJSON("map-v2.geojson",function(data){
var bev = L.geoJson(data,{
pointToLayer: function(feature,latlng){
var marker = L.marker(latlng);
marker.bindPopup('<p align=center>' + '<strong>Title: </strong>' + feature.properties.Title + '<strong>Date: </strong>' + feature.properties.Date + '<br/>' + '<strong>Creator: </strong>' + feature.properties.Creator);
return marker;
}
});
bev.addTo(map);
});
First, I set a variable that calls $.getJSON, which takes a few arguments, the first one is the name of the geoJSON file in quotes, and the second is function(data) which acts to say we are going to use the data found in this file. The second line I assign my variable bev to invoke the L.geoJson function, passing the argument data (which will use the data from the geoJSON file). Then I point to a new layer using pointToLayer and assigning it the value of the function(feature,latlng). feature allows me to name certain properties from my geoJSON file to display in the popups, latlng extracts the coordinates from the geoJSON file to generate the locations for the markers(latlng is mandatory). I then assign another variable called marker, and here's where you generate your markers on your map, simply by using L.marker(latlng). After that, the marker.bindPopup binds all the content I want to display on popups from the properties data I have in each of my points in the geoJson file. Here's an example of my geoJSON:
{
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-122.714055,
38.440429
]
},
"properties": {
"Title": "Santa Rosa. Sonoma County. California. 1885.",
"Date": "1885",
"Creator": "W.W. Elliot & Co., lithographer."
}
},
I then return the marker, add the variable bev to the map, and there they are!
*I'm not an expert on JavaScript or Leaflet, so if my wording is off, I will gladly make edits to make it clearer.
Implementing the Leaflet Search example just produces a search box. Nothing happens when you open it and start typing. The leaflet search code isn't being executed. It just shows the red Location not found. The graph shows area's of interest and I need to do something with the area's that match search criteria, to identify them to the user.
var searchLayer = L.layerGroup().addTo(map);
//... adding data in searchLayer ...
map.addControl( new L.Control.Search({layer: searchLayer}) );
//searchLayer is a L.LayerGroup contains searched markers
There is code in the control to search to the data. It takes into account a geoJson data structure.
What am I missing in order to activate the search code?
Although not explicitly explained in Leaflet Control Search README, the plugin will use the data in marker.options.title or in feature.properties.title by default.
You can specify a different key than title using the propertyName option when instantiating the Search Control:
var map = L.map('map').setView([41.8990, 12.4977], 14);
var poiLayers = L.geoJSON(restaurant, {
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties.amenity + '<br><b>' + feature.properties.name + '</b>');
}
});
L.control.search({
layer: poiLayers,
initial: false,
propertyName: 'name' // Specify which property is searched into.
})
.addTo(map);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap'
}).addTo(map);
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet-src.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet-search#2.3.7/dist/leaflet-search.src.css" />
<script src="https://unpkg.com/leaflet-search#2.3.7/dist/leaflet-search.src.js"></script>
<script src="http://labs.easyblog.it/maps/leaflet-search/examples/data/restaurant.geojson.js"></script>
<div id="map" style="height: 200px"></div>
I have a polygon data stored in mysql column "poligon" with structure like this
(lat, long)(lat,long)...
'(-6.811408423530006, 110.85068956017494)(-6.811770629167109,
110.85174098610878)(-6.81129656585151, 110.85196629166603)(-6.810718634097109, 110.85200116038322)(-6.8106946645623, 110.85195824503899)(-6.811046217619413, 110.85130110383034)'
how to enter this data to polygon code HERE Map Js API bellow
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link rel="stylesheet" type="text/css"href="https://js.api.here.com/v3/3.0/mapsjs-ui.css" />
<script type="text/javascript" charset="UTF-8" src="https://js.api.here.com/v3/3.0/mapsjs-core.js"></script>
<script type="text/javascript" charset="UTF-8" src="https://js.api.here.com/v3/3.0/mapsjs-service.js"></script>
<script type="text/javascript" charset="UTF-8" src="https://js.api.here.com/v3/3.0/mapsjs-ui.js"></script>
<script type="text/javascript" charset="UTF-8" src="https://js.api.here.com/v3/3.0/mapsjs-mapevents.js"></script>
</head>
<body>
<div id="map" style="width: 100%; height: 400px; background: grey" />
<script type="text/javascript" charset="UTF-8" >
/**
* Adds a polygon to the map
*
* #param {H.Map} map A HERE Map instance within the application
*/
function addPolygonToMap(map) {
var geoStrip = new H.geo.Strip(
[52, 13, 100, 48, 2, 100, 48, 16, 100, 52, 13, 100], 'values lat lng alt'
);
map.addObject(
new H.map.Polygon(geoStrip, {
style: {
fillColor: '#FFFFCC',
strokeColor: '#829',
lineWidth: 8
}
})
);
}
/**
* Boilerplate map initialization code starts below:
*/
//Step 1: initialize communication with the platform
var platform = new H.service.Platform({
app_id: 'DemoAppId01082013GAL',
app_code: 'AJKnXv84fjrb0KIHawS0Tg',
useCIT: true,
useHTTPS: true
});
var defaultLayers = platform.createDefaultLayers();
//Step 2: initialize a map - this map is centered over Europe
var map = new H.Map(document.getElementById('map'),
defaultLayers.normal.map,{
center: {lat:52, lng:5},
zoom: 5
});
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Create the default UI components
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Now use the map as required...
addPolygonToMap(map);
</script>
</body>
</html>
how to replace this data bellow with my polygon data structure (lat, long)(lat, long)...
new H.geo.Strip(
[52, 13, 100, 48, 2, 100, 48, 16, 100, 52, 13, 100], 'values lat lng alt'
);
sorry i'm newbie
Assuming you are retrieving the data for the polygon as a string on the javascript side, you should be able to use simple String manipulation.
var latLonString="(-6.811408423530006, 110.85068956017494)(-6.811770629167109, 110.85174098610878)(-6.81129656585151, 110.85196629166603)(-6.810718634097109, 110.85200116038322)(-6.8106946645623, 110.85195824503899)(-6.811046217619413, 110.85130110383034)";
//to remove first '(' and last ')'
latLonString=latLonString.substring(1,latLonString.length -2);
// get individual coordinates
var latLonValues=latLonString.split("\)\(");
var finalArray=[];
for(i=0;i<latLonValues.length;i++){
var latLonSperated=latLonValues[i].split(",");
finalArray.push(parseFloat(latLonSperated[0]));
finalArray.push(parseFloat(latLonSperated[1]));
// no altitude
finalArray.push(0);
}
var polystrip1 = new H.geo.Strip(finalArray);
var polygon1 = new H.map.Polygon(polystrip1);
map.addObject(polygon1);
I have problem with the execution of the javascript inside a jsp page.
I have the following page which works perfectly if I call it from my filesystem, that is, I write in the address bar C:\...\heatmap2.jsp.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Energy Heatmap </title>
<style>
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 80% }
h1 { position:absolute; }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization&sensor=true?key=AIzaSyCzoFE1ddY9Ofv0jjOvA3yYdgzV4JvCNl4"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type='text/javascript'>
/*Array in cui saranno inseriti i punti da visualizzare nella mappa
*/
var heatMapData = new Array();
function loadHeatMapData(callback)
{
$.ajax
({
type: "GET",
url: "http://localhost:8080/EnergyManagement-portlet/api/secure/jsonws/sample/get-samples-time-by-name?energyName=EnAssGS",
dataType: "jsonp",
crossDomain: true,
cache: false,
success: function(jsonData)
{
for (var i = 0; i < jsonData.length; i++)
{
var decodedData = JSON.parse(jsonData[i]);
var lng = decodedData["_longitude"];
var lat = decodedData["_latitude"];
var energyIntensity = decodedData["_value"];
heatMapData.push({location: new google.maps.LatLng(lat, lng), weight: energyIntensity});
}
return callback(heatMapData);
}
})
}
function drawHeatMap()
{
// map center
var myLatlng = new google.maps.LatLng(40.8333333, 14.25);
// map options,
var myOptions = {
zoom: 5,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
// standard map
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var heatMap = new google.maps.visualization.HeatmapLayer({
data: heatMapData,
dissipating: false
});
heatMap.setMap(map);
/*
Questi punti dovrebbero prevenire da un file.
*/
var vehiclePath = [
new google.maps.LatLng(40.85235, 14.26813),
new google.maps.LatLng(40.85236, 14.26822),
new google.maps.LatLng(40.85236, 14.26822),
new google.maps.LatLng(40.85236, 14.26816),
new google.maps.LatLng(40.85258, 14.26811),
new google.maps.LatLng(40.85364, 14.26793),
new google.maps.LatLng(40.85414, 14.26778),
new google.maps.LatLng(40.8554, 14.2676),
new google.maps.LatLng(40.8579, 14.27286),
new google.maps.LatLng(40.85821, 14.27291),
new google.maps.LatLng(40.8584, 14.27302),
new google.maps.LatLng(40.85859, 14.27325),
new google.maps.LatLng(40.8587, 14.27421),
new google.maps.LatLng(40.85865, 14.27433),
new google.maps.LatLng(40.85866, 14.27446),
new google.maps.LatLng(40.86656, 14.291),
new google.maps.LatLng(40.86653, 14.29102)
];
var path = new google.maps.Polyline({
path: vehiclePath,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
path.setMap(map);
}
/*Callback*/
loadHeatMapData(drawHeatMap)
</script>
</head>
<body>
<div id="map-canvas"></div>
<p id="demo"></p>
</body>
</html>
Unfortunately, when I try to call it inside my Liferay portal, I can't see any javascript running.
The following code creates a heatmap (with the Google API), the points are obtained with an asynchronous call to the webserver
via SOAP (it's a method available from an entity of my project).
I also tried to add the tag
<header-portlet-javascript>
"https://maps.googleapis.com/maps/api/js?libraries=visualization sensor=true?key=AIzaSyCzoFE1ddY9Ofv0jjOvA3yYdgzV4JvCNl4"
</header-portlet-javascript>
with no sucess.
Any help is appreciated.
Without being able to test your code currently, I see two issues with it:
Your JSP contains <html>, <head> and <body> elements etc. These are not allowed in portlets and won't work the same way as in a standalone page
Further, your contains superfluous quotes.
<header-portlet-javascript>
"https://maps.googleapis.com/and/so/on"
</header-portlet-javascript>
I'd expect this to literally be added to the page, resulting in double quotes
<script type="text/javascript" src=""https://maps.googleapis.com/and/so/on""></script>
Obviously, this doesn't work. Please check what ends up on the generated page when you add your portlet to it. Also, remove the extra quotes and try again.
Deae Olaf,
I applied your advice to my code.
With the support of the internet explorer debbuger, I found out that the code inside the drawHeatmpaData is like being commented (please, look at the picture)
.
In order to prevent from you code being commented, I found that we cannot use // to comment,
because all the text even the code is treated as comment.
I replace all // with /**/ but it still does not work.
I implemented the map on web page using JavaScript API, and now I want to show the basic information about some location. In JavaScript API documentation, I found a part of which is called "Basic place display" in Places Components section, but there is an example of how to render information using placeId.
I need to be able to retrieve information using location coordinates if it is possible. I tried to display information using PHP code that define coordinates for some location on the map instead of using placeId, but it's not working.
This is an example of code that I used:
var basicPlace = new nokia.places.widgets.Place({
placeId: PHP code instead of placeId.
*exp: [<?php code;?>, <?php echo code;?>],*
targetNode: "map",
template: "nokia.blue.place"
});
Is it possible to solve the problem like that, or there is a method that does not involve placeId.
Links: Here Developer, Here JavaScript API
If you read the nokia.places.widgets.Place documentation, you will see that placeId is a mandatory parameter. It is in effect the primary key for the place information that is held by HERE. You will therefore need to make another request using the JavaScript API prior to display in order to obtain the placeId so you can show your place details. The obvious thing to do here is to make a category request first, and store the placeId with each marker as shown below:
// Function for receiving search results from places search and process them
var processResults = function (data, requestStatus, requestId) {
var i, len, locations, marker;
if (requestStatus == "OK") {
locations = data.results ? data.results.items : [data.location];
if (locations.length > 0) {
for (i = 0, len = locations.length; i < len; i++) {
// Add a marker and store the placeId
marker = new nokia.maps.map.StandardMarker(locations[i].position,
{ text: i+1 ,
placeId : locations[i].placeId});
resultSet.objects.add(marker);
}
}
});
// etc.. etc...
The second part is to add the click listener which displays an infobubble and populates the Place Widget using the stored placeId:
resultSet.addListener("click" , function(evt) {
infoBubbles.openBubble("<div id='basicPlaceContainer'></div>",
evt.target.coordinate);
var basicPlace = new nokia.places.widgets.Place({
placeId: evt.target.placeId,
targetNode: "basicPlaceContainer",
template: "nokia.blue.bubble"
});
}, false);
The complete working example can be seen below:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9; IE=10" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Nokia Maps API for JavaScript Example: Search by category</title>
<meta name="description" content="Search by category"/>
<script type="text/javascript" charset="UTF-8" src="http://js.cit.api.here.com/se/2.5.3/jsl.js?with=all"></script>
</head>
<body>
<div id="mapContainer" style="width:540px; height:334px;"></div>
<script type="text/javascript" id="exampleJsSource">
/* Setup authentication app_id and app_code
*/
nokia.Settings.set("app_id", "YOUR APP ID");
nokia.Settings.set("app_code", "YOUR APP CODE");
// Use staging environment (remove the line for production environment)
nokia.Settings.set("serviceMode", "cit");
// Get the DOM node to which we will append the map
var mapContainer = document.getElementById("mapContainer");
// Create a map inside the map container DOM node
var map = new nokia.maps.map.Display(mapContainer, {
// Initial center and zoom level of the map
center: [52.51, 13.4],
zoomLevel: 10,
components: [
new nokia.maps.map.component.Behavior()
]
});
this.infoBubbles = new nokia.maps.map.component.InfoBubbles();
map.components.add(infoBubbles);
var searchCenter = new nokia.maps.geo.Coordinate(52.51, 13.4),
searchManager = nokia.places.search.manager,
resultSet;
// Function for receiving search results from places search and process them
var processResults = function (data, requestStatus, requestId) {
var i, len, locations, marker;
if (requestStatus == "OK") {
locations = data.results ? data.results.items : [data.location];
if (locations.length > 0) {
if (resultSet) map.objects.remove(resultSet);
resultSet = new nokia.maps.map.Container();
resultSet.addListener("click" , function(evt) {
infoBubbles.openBubble("<div id='basicPlaceContainer'></div>", evt.target.coordinate);
var basicPlace = new nokia.places.widgets.Place({
placeId: evt.target.placeId,
targetNode: "basicPlaceContainer",
template: "nokia.blue.bubble"
});
}, false);
for (i = 0, len = locations.length; i < len; i++) {
marker = new nokia.maps.map.StandardMarker(locations[i].position,
{ text: i+1 ,
placeId : locations[i].placeId});
resultSet.objects.add(marker);
}
map.objects.add(resultSet);
map.zoomTo(resultSet.getBoundingBox(), false);
} else {
alert("Your search produced no results!");
}
} else {
alert("The search request failed");
}
};
// Make a place search request
var category = "eat-drink";
map.addListener("displayready", function () {
searchManager.findPlacesByCategory({
category: category,
onComplete: processResults,
searchCenter: searchCenter
});
});
</script>
</body>
</html>
The result can be see below: