Here Maps API - Basic place display (placeId) - javascript

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:

Related

importe markers from database usin HERE MAPS API

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

Getting data from python with JS and plotting it, with Django backend and Google maps api

I've got a project with a django backend that I'm using for logins, and using the mysql DB through my local host. I currently have my gettweets.py script returning an array of coordinates and have a JS script that is supposed to get these results and plot it to google maps api. My JS script fails at $.get. However, if i go to 127.0.0.1/gettweets?tag=%23Pizza, I get something like this:
["-87.634643, 24.396308", "-80.321683, 25.70904", "-79.639319, 43.403221", "-95.774704, 35.995476", "-84.820309, 38.403186", "-120.482386, 34.875868", "-121.385009, 38.716061", "-111.530974, 40.619883"]
I've been trying to get JS to make the call on the button click because I don't think I can get the results to it through Django. Why is it getting stuck?
Here is the JS inside of index.html
<script type="text/javascript">
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(49.13,-100.32),
mapTypeId: 'roadmap'
});
}
// Loop through the results array and place a marker for each
// set of coordinates.
$('#searchButton').click(function(){
$.get('../../gettweets?tag=%23Trump', function(data, status) {
alert(status);
var data = JSON.parse(this.response);
alert('data');
data.forEach(function(point) {
var coordString = point['coord'];
var x = coordString.substring(0,coordString.indexOf(','));
var y = coordString.substring(coordString.indexOf(',')+1,coordString.length);
console.log(x);
console.log(y);
var coords = results.features[i].geometry.coordinates;
var latLng = new google.maps.LatLng(x,y);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
});
window.myLine.update();
});
//xmlhttp = new XMLHttpRequest();
//var tag = document.getElementById('tagSearch').value;
//if (this.readyState === 4 && this.status === 200) {
//}
//xmlhttp.open("GET","./getTweets.php?tag='" + tag + "'");
//xmlhttp.send();
});
</script>
Button/form:
<form>
<input id="tagSearch" type="text" name="tag" maxlength="100" required placeholder="{{ tag }}" />
<button class="btn waves-effect red" type="submit" id="searchButton" name="search">Submit
<i class="material-icons right">send</i>
</button>
</form>
gettweets.py - NOTE I've got this in my views, as well as a separate file. I'm not sure which one I need with the JS
def tweets(request):
tag = request.GET['tag']
print(tag)
x = models.Tweet.objects.filter(tag=tag)
print(x)
coords = []
for i in x:
coords.append(i.coord)
print(coords)
return JsonResponse(coords, safe=False)
Finally, urls
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^gettweets$', views.tweets, name='gettweets'),
]
You're calling $.get() incorrectly. Its signature is $.get(url[, data][, success][, dataType]), from the docs.
I would prefer using a settings object like so:
$.get({
url: '../../gettweets?tag=%23Hillary',
success: function (data, status) {
...
}
});

Google maps v3 api, center map based on location

I'm trying to center my map based on the location of the visitor, but somehow it doesn't work.
I have a PHP variable containing the country code of my visitor, which works fine when i check the source code in my browser. It looks like this;
<head>
...
<script type="text/javascript">
var lang = <?php echo $lang; ?>;
</script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body onload="initialize()">
...
My script.js contains these lines;
function initialize() {
if (lang == NL) {
var centerlat = 52.150892;
var centerlng = 5.534668;
var zoomlvl = 7;
}
else {
var centerlat = 52.367896;
var centerlng = 5.219407;
var zoomlvl = 13;
}
var myLatlng = new google.maps.LatLng(centerlat,centerlng);
var myOptions = {
zoom: zoomlvl,
center: myLatlng,
...
}
map = new google.maps.Map(document.getElementById("kaart"), myOptions);
When i load the page containing the map it just doesnt appear. In the source code i can see the PHP variable displaying correctly.
Firebug says lang is undefined. Any idea whats going on here?
//edit: I have another variable done in the same way which works fine. But its outside the initialize function.
Solved: Forgot quotes ^^
Try surround NL with "".
As an aside have you looked into HTML 5 geolocation? Its relatively simple to implement and will give you a much more accurate location.
Take a look here: https://developers.google.com/maps/documentation/javascript/examples/map-geolocation and here:http://www.w3schools.com/html/html5_geolocation.asp
Any idea whats going on here?
sorry, I don't have the rep to 'comment'
Is NL a string variable or a value (should it be "NL" ?)

fetch for defects not fetching across user, iteration, and project

I have researched and tried everything that I can think of to try and retrieve the actual values for the Iteration, Project, and User columns but I can never get the column data to populate for those like the name of the iteration, name of the project, and name of the submitted by user. I have read that it should be fine to do in the fetch the way I have it and others have said that you have to specify the types with something like this
types : ['defect','user','iteration','project'],
When I do that I dont ever load my grid. I have tried things like this as recommended by some
defect.Iteration.Name
OR
Iteration.Name
I could really use some help here. I also read one article saying the WSAPI no longer supports this kind of request and has to be handled in multiple queries/fetches. Anywho, here is the code that I am using...
function onLoad() {
var rallyDataSource = new rally.sdk.data.RallyDataSource(
'__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
var config = {
type : 'defect',
key : 'defects',
columnKeys : ["FormattedID", "Name", "Priority125", "Iteration", "Project", "SubmittedBy", "CreationDate", "ScheduleState", "State"],
fetch : 'FormattedID,Name,Priority125,Iteration,Project,SubmittedBy,CreationDate,ScheduleState,State',
query : '((State != "Closed") OR (ScheduleState != "Accepted"))',
order : 'Priority125'
};
var table = new rally.sdk.ui.Table(config, rallyDataSource);
table.display("tableDiv");
}
rally.addOnLoad(onLoad);
There are several things needed in order to get this to work as you're wanting:
You can fetch recursively up to a level of one deep. Thus if you want to grab a Defect's Name, Formatted ID, and the Project Name, your fetch would look like:
fetch: "Name,FormattedID,Project,Name"
Grab the data via rallyDataSource.findAll()
Post-process the data so that you feed your table all string data. I.e. clobber Object Reference fields like Project, with the Project Name instead.
Finally, populate and display the table.
Here's working example that illustrates what I think you're wanting to do (minus the "Priority 125" custom field that you have defined).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Copyright (c) 2011 Rally Software Development Corp. All rights reserved -->
<html>
<head>
<title>Defect Information</title>
<meta name="Name" content="Defect Information" />
<meta name="Version" content="1.32" />
<meta name="Vendor" content="Rally Software" />
<script type="text/javascript" src="https://rally1.rallydev.com/apps/1.32/sdk.js?debug=True"></script>
<script type="text/javascript">
var rallyDataSource = null;
var table = null;
function showTable(results) {
if (table) {
table.destroy();
}
var tableConfig = {
columnKeys : ["FormattedID", "Name", "Iteration", "Project", "SubmittedBy", "CreationDate", "ScheduleState", "State"],
columnWidths : ["85px", "350px", "90px", "100px", "100px", "120px", "100px", "100px" ]
};
table = new rally.sdk.ui.Table(tableConfig);
// Loop through the rows and clobber object attributes of the results collection with
// string values
for(var i = 0; i < results.defects.length; i++){
thisDefect = results.defects[i];
var iterationName = "";
// Grab value fields
if (thisDefect.Iteration != null) {
iterationName = results.defects[i].Iteration.Name;
} else {
iterationName = "Un-scheduled";
}
var projectName = thisDefect.Project.Name;
// Re-map SubmittedBy object to SubmittedBy string
submittedByDisplayName = thisDefect.SubmittedBy === null ? "": thisDefect.SubmittedBy._refObjectName;
// Clober objects with values
results.defects[i].Iteration = iterationName;
results.defects[i].Project = projectName;
results.defects[i].SubmittedBy = submittedByDisplayName;
}
table.addRows(results.defects);
table.display(document.getElementById('defectsDiv'));
}
function onLoad() {
rallyDataSource = new rally.sdk.data.RallyDataSource(
'__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
var config = {
type : 'defect',
key : 'defects',
fetch: 'FormattedID,Name,SubmittedBy,Iteration,Name,Project,Name,CreationDate,ScheduleState,State',
query : '((State != "Closed") OR (ScheduleState != "Accepted"))',
};
rallyDataSource.findAll(config, showTable);
rallyDataSource.setApiVersion("1.38");
}
rally.addOnLoad(onLoad);
</script>
</head>
<body>
<div id="aDiv"></div>
<div style="font-weight: bold;"><p>Defects</p></div>
<div id="defectsDiv"></div>
</body>
</html>

Google maps get latitude and longitude having city name?

I want to get latitude and longitude of a city by providing the API with the city name. It should work for most cities regardless how the user inputs the city.
For example:
City can be 'miami, US' or city can be 'miami, united states'
How do I print its latitude?
You can find the code jsfiddled here : http://jsfiddle.net/YphZw/
or below :
$("#btn").click(function(){
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': 'miami, us'}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng());
} else {
alert("Something got wrong " + status);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
</head>
<body>
<input id="btn" type="button" value="search for miami coordinates" />
</body>
</html>
If you want more examples for the Javascript API, try this link : https://developers.google.com/maps/documentation/javascript/examples/
The code I wrote is inspired from the geocoding-simple sample.
Regards.
EDIT 1:
You can achieve it using an non-official PHP library. Check this example :
http://www.bradwedell.com/phpgooglemapapi/demos/geocoding.php
(The code is at the bottom=
You can use Google's geocoding service, e.g.,
http://maps.googleapis.com/maps/api/geocode/xml?address=Miami+FL&sensor=false
That gives you back georeferenced data in a variety of formats (JSON, XML, etc). In any event, the location is definitely in the returned data block.
The API docs are at:
https://developers.google.com/maps/documentation/geocoding/
Update per comment below: Doesn't work after July 2018.
This seems needlessly complicated. Here's an example "nearby events" map. It will take City, States, convert them to latLng coords, and put markers on a map:
// Nearby Events with Google Maps
window.nearbyEventsMap = () => {
const centerOfUS = {
lat: 37.09024,
lng: -95.712891
}
// Create a map object and specify the DOM element for display.
const map = new google.maps.Map(document.querySelector('#nearby_events_map'), {
center: centerOfUS,
scrollwheel: false,
zoom: 4
})
// Create a marker and set its position.
const geocoder = new google.maps.Geocoder()
// Filter out duplicate cityStates
let cityStates = {}
document.querySelectorAll('.nearby_event_city_state').forEach(event => {
cityStates[event] = event.innerText
})
// `cityState` is in the format of "City, State". It's not picky about state being a word or the abbreviation.
for (const cityState in cityStates) {
const location = cityStates[cityState]
geocoder.geocode({
address: location
}, function (results, status) {
if (status === 'OK') {
const result = results[0].geometry.location
const lat = result.lat()
const lng = result.lng()
const latLng = {
lat,
lng
}
return new google.maps.Marker({
map: map,
position: latLng
})
}
})
}
}
// /Nearby Events with Google Maps
Make sure to include your <script> tags.
<script src="/dist/js/main.js"></script>
<!-- We're loading this after the main.js script so the callback from main.js will be available to it. -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=nearbyEventsMap"></script>
StackOverflow please join everyone else and get GitHub markdown with syntax highlighting...

Categories

Resources