Google Map markers and JSON object - javascript

I have a database which stores the position of markers previously added on the Google Map (Latitude/Longitude). What I want to do now, it's to create a function which takes a JSON object as a parameter, containing those markers position and add automatically the markers in the map. I start to get the markers from my database and try to loop on the JSON object which looks like this:
{"markers":"\"[{\\\"k\\\":48.80686346108517,\\\"B\\\":1.494140625},{\\\"k\\\":50.28933925329177,\\\"B\\\":14.326171875},{\\\"k\\\":43.70759350405294,\\\"B\\\":21.357421875},{\\\"k\\\":30.977609093348686,\\\"B\\\":11.337890625},{\\\"k\\\":40.58058466412761,\\\"B\\\":-0.87890625},{\\\"k\\\":48.45835188280866,\\\"B\\\":1.318359375}]\""}
Here is the current state of my code:
//Create a new set of markers based on received position.
function createMarkerBasedOnFetchedPosition(fetchedMarkersPosition)
{
var jsonData = JSON.parse(fetchedMarkersPosition);
alert(fetchedMarkersPosition);
map.addMarker({
lat: ? //Fetched from the JSON object parsing.
lng: ? //Fetched from the JSON object parsing.
animation: google.maps.Animation.DROP
});
Can anyone please help me to build this, I don't know yet how to deal with a JSON object to retrieve the Latitude/Longitude. I'm looking for a JavaScript solution only. Thanks for your help!

From your current code you would then need to loop through the markers with a for loop like so and add a marker to the map:
var data = '{"markers":[{"k":48.80686346108517,"B":1.494140625},{"k":50.28933925329177,"B":14.326171875},{"k":43.70759350405294,"B":21.357421875},{"k":30.977609093348686,"B":11.337890625},{"k":40.58058466412761,"B":-0.87890625},{"k":48.45835188280866,"B":1.318359375}]}';
function createMarkerBasedOnFetchedPosition(fetchedMarkersPosition)
{
var jsonData = JSON.parse(fetchedMarkersPosition);
for (var i = 0; i < jsonData.markers.length; i++) {
map.addMarker({
lat: jsonData.markers[i].k,
lng: jsonData.markers[i].b,
animation: google.maps.Animation.DROP
});
}
}
createMarkerBasedOnFetchedPosition(data);

Related

Loop for new Google Map Marker for every JSON object in database

I'm working with a friend to create a Google Map marker for every entry in a table - I have a loop but I'm not sure I've got it right. The map works fine, I can add normal markers and can loop through the entries and append them to a div but when I try to use the marker code in the loop I get the following errors for every entry in the console:
InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number
InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama
Does this mean that the database isn't saving the lat/long as a number? Here is a shorter version of the code I'm using:
$.ajax({
type: 'POST',
url: 'getAllJson.php',
success: function(jsonData) {
var obj = (jsonData);
$.each(obj, function(key,value) {
//console.log(key, first, value[1], value[2]);
var user = {
id: value["id"],
firstName: value["first_name"],
lastName: value["last_name"],
email: value["email"],
lat: value["latitude"],
long: value["longitude"]
};
var firstName = user.firstName,
lastName = user.lastName,
email = user.email,
userLat = user.lat,
userLong = user.long;
// marker
var markerLatLng = {lat: userLat, lng: userLong};
var marker = new google.maps.Marker({
position: markerLatLng,
map: map
});
});
}
});
Am I on the right track or is there a better/easier way to loop through all the entries and create a marker based on the lat/long? Thanks!
You have to solve two problems here.
The first is to parse userLat/ userLong to floats. This can be done as mentioned above in my comment:
var markerLatLng = {lat: parseFloat(userLat), lng: parseFloat(userLong)};
The other Problem you are facing is, that you map instance isnĀ“t reachable, because you have defined it locally in initMap. To fix this, you simply make
var map;
function mapInit(){
map = new google.maps.Map('');
}
This should do it.

Leaflet: How to save various marker position in db and load later

i am just forking with leaflet because in future i may have to work.
see few url
http://justinmanley.github.io/Leaflet.Illustrate/examples/0.0.2/simple/
http://leaflet.github.io/Leaflet.toolbar/examples/control.html#
if anyone go to that url then must realize user can place marker on map or place square or circle on map. so my question how to save those marker position in db as a result when i will show that map then i can place those marker again on map from db if i could know their position and saving into db.
if i need to save various marker position in db then how the table structure would look like for sql server.
please discuss my two points or redirect me to relevant article which help me to achieve this.
thanks
I would do something like this:
var map = L.map('mapcanvas').setView([51.505, -0.09], 13);
map.on('click', function(e){
// Place marker
var marker = new L.marker(e.latlng).addTo(map);
// Ajax query to save the values:
var data = {
lat: e.latlng.lat,
lng: e.latlng.lng
}
var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
});
Although it is probably better to use jQuery.
You would then obtain your saved values from the database, store them in a js object, like
var positions = [
{
lat: 123.45
lng: 123.45
},
{
lat: 123.45
lng: 123.45
}
]
Iterate over them and add markers:
for (var i in positions) {
new L.marker([positions[i].lat, positions[i].lng]).addTo(map);
}

Using Jade Array in Javascript transforms it to a string

I am passing an array of objects to my jade template, and want to use it as var in my js.
it seems to be transferred correctly, as
each level, i in stats
.levelStats
creates 4 divs (as expected)
now i have
script(type='text/javascript').
var statData = "!{stats}"
which, as far as i know, should load the data into a javascript var.
it does that, in a way...
console.log(statData);
// output: [object Object],[object Object],[object Object],[object Object]
// this means the correct data must be there..somewhere
console.log(typeof statData);
// output: string
what am I doing wrong?
how can i get the whole array into the var?
solution + lesson:
var foo = "!{bar}" makes the data a string (pretty obvious in restrospective)
right way to go: var foo = !{bar}
each level, i in stats
.levelStats
You are looping over (an array ?) stats where i is an index and level the element of your array at stats[i].
but you don't seem to use the elements separatly :
var statData = "!{stats}"
stats still the array, you will find each element in level !
Edit :
After clarification, to keep the whole array and set it to a variable :
var statData = !{JSON.stringify(stats)}
You need to put a string in the <script> tag. How to make array into a string, so that you can convert it back later? JSON.stringify.
So, something like this should work:
script.
var statData = !{JSON.stringify(stats)};
I spent full day to make it work. It is more advanced example, but we pass array to js in jade/pug file. Here we pass array of locations to google maps init script. Use it like this:
1)Prepare data on the server
JSON.stringify(locations = [
{ lat: -31.563910, lng: 147.154312 },
{ lat: -33.718234, lng: 150.363181 },
{ lat: 52.319277, lng: 21.000466 }
])
2)pass it to your pug/jade page.
There, use this with variable that you pass, for example: DATA_THAT_YOUPASS
script.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 52.5191758, lng: 23.0002262}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var mydata = !{DATA_THAT_YOUPASS}
console.log(mydata);
console.log(mydata);
var locations = mydata;
#map
script(src='https://unpkg.com/#google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js')
// Replace the value of the key parameter with your own API key.
script(async='', defer='', src='https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXXXXXX&callback=initMap')

additional selections in Google maps api (3)

Once I have created a map with multiple markers using google maps API, I want to additional selections to highlight a subset of markers displayed. I would like to do this without going back to the server. Preferably I would like to store data in marker or array. I could either substitute with new marker or overlay an image on top of the marker. Can anyone propose example of how to do this - specifically part about adding image or change marker.
Example below...
Here's an example, which assumes that when you load your page you have this data returned from the server in JSON.
data = [{
latitude: 103.2,
longitude: 12.3,
isDiscountOutlet: false
}, {
latitude: 101.2,
longitude: 11.3,
isDiscountOutlet: false
}
]
The basic approach is that we store that data in the browser, and use it to update the appearance of markers when changing a selection.
Part 1: Create a global variable to store our markers in
var storedMarkers;
Part 2: Create a Map using the data from the server
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(103, 11)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Add the markers. We are going to store them in a global array too,
// so we can access them later.
for (var i = 0; i < data.length; ++i) {
// Create one marker for each piece of data.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i].latitude, data[i].longitude),
map: map
});
// Store that marker, alongside that data.
var dataToStore = {
markerObject: marker,
dataAssociatedWithMarker: data[i]
};
storedMarkers.push(dataToStore);
}
google.maps.event.addDomListener(window, 'load', initialize);
Part 3: Let's show all discount outlets, and hide all other markers, when someone clicks a button
I'm assuming you have a DOM element (a button) with id 'discount'. I'm also going to cheat and use jQuery :)
$("#discount").click(function () {
for (var i = 0; i < storedMarkers.length; ++i) {
var currentStoredMarker = storedMarkers[i];
// Is this marker a discount outlet?
if (currentStoredMarker.dataAssociatedWithMarker.isDiscountOutlet == true) {
// Let's show it!
currentStoredMarker.markerObject.setVisible(true);
} else {
// Let's hide it!
currentStoredMarker.markerObject.setVisible(false);
}
}
});

Correct way to iterate through a Json structure in Javascript for locate google maps marker

I'd like to know why this function dont place any marker in my map.
im passing from my servlet to jsp an object marker that contains his title and the coordinate, this is a sample
<%=request.getAttribute("markers")%> = [{"lat":10.0,"lng":10.0,"title":"place"}];
and this is the javascript function
function placeMarker() {
var json = <%=request.getAttribute("markers")%>;
var obj = JSON.parse(json);
for(var i in obj){
var lat = obj[i].lat;
var lng = obj[i].lng;
var title = obj[i].title;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
icon: icon,
title: title
});
}
}
thank you for any suggestion and sorry for the bad english :D
JSON is a string try something like this:
var json = '<%=request.getAttribute("markers")%>';

Categories