Looping in Javascript, multiple variables [closed] - javascript

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have a MySQL database from which I fetch data to show a marker on my Google map. I would want to show n markers but I don't know how to implement for-loop so that
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!',
});
would repeat n-times. I've tried adding for loop function but I can't get it right. I'm only starting to learn JavaScript.
Here's the rest of the code: http://jsfiddle.net/Wkn9v/7/
Thank you!

What did you try? A for loop works fine http://jsfiddle.net/Wkn9v/3/
for(var i=0; i < 3; i++) {
var myLatlng = new google.maps.LatLng(-25.363882 + i/2, 131.044922);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!',
});
}
Maybe you're using the same lat/long in your loop? If so, they're on top of each other, and it looks like a single marker?

I modified your code so the logic is performed in the initialize function, because otherwise the loop wasn't executing properly. There was some other stuff in the wrong places too. This works:
jQuery(function ($) {
var map_canvas = document.getElementById('map_canvas');
$.getJSON('http://www.wawhost.com/appProject/fetchmarker.php?callback=?', function (data) {
initialize(data);
});
function initialize(data) {
var myLatlng = new google.maps.LatLng(-25.363882, 131.044922),
mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(map_canvas, mapOptions),
pos, lat, lng, latlang, marker;
for (var i = 0, l = data.length; i < l; i++) {
localStorage.loc = data[i].location;
pos = localStorage.loc.split(",");
lat = parseFloat(pos[0]);
lng = parseFloat(pos[1]);
latlang = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: latlang,
map: map,
title: 'Hello World!' // <<< Keep in mind that trailing , that was here is unnecessary
});
}
}
});
http://jsfiddle.net/userdude/Wkn9v/13/

You can use a for loop like this:
var myLatlng = [
new google.maps.LatLng(-10.0, 10.0),
new google.maps.LatLng(-10.2, 10.0),
new google.maps.LatLng(-10.0, 10.2)
];
var marker;
for(var i = 0; i < myLatlng.length; i++) {
marker = new google.maps.Marker({
position: myLatlng[i],
map: map,
title: 'Hello World!',
});
}

Here's what you need to do: http://jsfiddle.net/Wkn9v/10/
The code is pretty simple:
function initialize(data) {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(-25.363882, 131.044922),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 4
});
var length = data.length;
for (var i = 0; i < length; i++) {
var loc = data[i].location;
var pos = loc.split(",");
var lat = +pos[0];
var lng = +pos[1];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map
});
}
}
Here's what it does:
Creates a map centered at a fixed location.
For each location fetched via AJAX it creates a new marker.

If you have a list to run through, and you don't need the list you're working with but to setup the markers or whatnot, you can use a queue-based method that iterates over the list until the list is empty:
jQuery(document).ready(function ($) {
(function initialize() {
var pos = localStorage.loc.split(","),
lat = parseFloat(pos[0]),
lng = parseFloat(pos[1]),
myLatlngs = [
new google.maps.LatLng(-25.0, 131.0),
new google.maps.LatLng(-26.0, 132.0),
new google.maps.LatLng(-24.0, 130.0)
],
myLatlngs,
mapOptions = {
zoom: 4,
center: myLatlngs[0],
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
while (myLatlng = myLatlngs.shift()) {
new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
}
})();
});
http://jsfiddle.net/userdude/Wkn9v/9/
By "list" here I'm referring to an array, not an objects properties. So assume you get something the following back from your fetch script:
data = [
{"id":"1","published":"yes","location":"-25.363882,131.044922"},
{"id":"2","published":"yes","location":" -24.96614015991296, 139.7900390625"},
{"id":"3","published":"yes","location":"-28.76765910569124, 128.3203125"}
];
while (localStorage.loc = data.shift()) {
pos = localStorage.loc.location.split(",");
lat = parseFloat(pos[0]);
lng = parseFloat(pos[1]);
latlang = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: latlang,
map: map,
title: 'Hello World!'
});
}
I'm not real sure what you're up to with localStorage.loc here, since you overwrite it each time. If you omit it, you could possible set while (pos = ...location.split(',')) instead. Just depends on what you're doing and how the data is being interacted with in your script.

Related

Error addListener is not a function

I have an error
location_marker.addListener is not a function
map initialization
function initAutocomplete() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 31.7917 , lng: 7.0926},
zoom: 3,
mapTypeId: 'roadmap'
});
running through a list of locations and placing a marker for each
var location_marker;
for (var i = 0; i < locations.length; i++) {
location_marker = markers.push(new google.maps.Marker({
map: map,
title: locations[i].title,
position: locations[i].location
}));
}
create an info window that displays every marker's title
var infowindow = new google.maps.InfoWindow({
content: location_marker.title
});
location_marker.addListener('click', function() {
infowindow.open(map, location_marker);
});
Based on the code you provided, which does not seem complete, I assume the following.
Your var locationMarker saves the result from markers.push which returns the length of the array to which an object (google.maps.Marker) was pushed.
Because locationMarker is a Number, it has no addListener method. You might want to do something like this instead:
location_marker = new google.maps.Marker({
map: map,
title: locations[i].title,
position: locations[i].location
})
markers.push(location_marker);

Google map dont work

I have this part of code, that should show pins on google map of certain locations.
<script>
$(document).ready(function () {
var map;
var elevator;
var myOptions = {
zoom: 1,
center: new google.maps.LatLng(0, 0),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = ['Sarajevo', 'Africa', 'Asia','North America','South America'];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location;
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map,
icon: "http://i.imgur.com/DOd1sH3.png"
});
});
}
});
<div id="map_canvas"></div>
Map shows up and everything works, but the pins of locations are not shown.
I really dont know why.
Seems like you are calling the constructor without a reference to a variable.
Try this:
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: "http://i.imgur.com/D0d1sH3.png"
});
Alternatively you can set the markers to the map by calling the setMap function
var marker = new google.maps.Marker({
position: latlng,
icon: "http://i.imgur.com/D0d1sH3.png"
});
marker.setMap(map);
Hope this helps

Google API multiple markers (addresses NOT latlong) displaying title (tool tip)

I'm trying to use the script made by user netbrain as found here on stackoverflow to also show the address title when the user clicks on the marker. It should be relatively simple but I'm lost.
Any ideas? I've tried numerous options but nothing seems to work. netbrain's code below:
var map;
var elevator;
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(0, 0),
mapTypeId: 'roadmap'
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=true', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map
title: addresses[0]
});
});
}
This answer assumes you're only after tool tip and not the infowindow.
The variables addresses and x cannot be used within the callback as the value of x will always be 5 (in this example, see length of addresses array). Instead look at the data object like so:
var map;
var elevator;
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(0, 0),
mapTypeId: 'roadmap'
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=true', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map
title: data.results[0].formatted_address
});
});
}
EDIT
For completeness the data object is the result of the geocoding API call. The formatted_address is a property of a match within the results, see https://developers.google.com/maps/documentation/geocoding/#GeocodingResponses
Use this code:
$(document).ready(function () {
var map;
var elevator;
var myOptions = {
zoom: 1,
center: new google.maps.LatLng(0, 0),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'click', function(evt) {
var info_window = new google.maps.InfoWindow({maxWidth: 500});
info_window.setContent('Content here');
info_window.setPosition(latlng);
info_window.open(map, marker);
});
});
}
});

Random marker on google maps Jquery

I'm trying to create a map where I can loop through an array of different locations. Then I want to set out the position of a random coordinate. So I want one coordinate to place a marker for me randomly each time I reload the page!
function initialize() {
//here is the starting for the map, where it will begin to show
var latlng = new google.maps.LatLng(59.2982762, 17.9970823);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//below are the markers coordinates, change it to your coordinates
var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
var i = 0;
function randAreas() {
var flagAreas = (Math.round(Math.random())-0.5);
}
var flagAreas = [
[59.2967322, 18.0009393],
[59.2980245, 17.9971503],
[59.2981078, 17.9980875],
[59.2982762, 17.9970823],
[59.2987638, 17.9917639],
[59.2987649, 17.9917824],
[59.2987847, 17.9917731],
[59.2988498, 17.991684],
[59.2988503, 17.9981593],
[59.3008233, 18.0041763],
[59.3014033, 18.0068793],
[59.3016619, 18.0137766]
];
return flagAreas;
flagAreas.sort(randAreas);
//script counts the array of coordinates
//for (var i = 0; i < flagAreas.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(flagAreas[i], flagAreas[i]),
map: map,
});
}
window.onload = initialize;
</script>
First, move your map variable outside of initialize in case you need to use it elsewhere in your code.
var map;
function initialize() {
var latlng = new google.maps.LatLng(59.2982762, 17.9970823);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
var flagAreas = [
[59.2967322, 18.0009393], [59.2980245, 17.9971503],
[59.2981078, 17.9980875], [59.2982762, 17.9970823],
[59.2987638, 17.9917639], [59.2987649, 17.9917824],
[59.2987847, 17.9917731], [59.2988498, 17.991684],
[59.2988503, 17.9981593], [59.3008233, 18.0041763],
[59.3014033, 18.0068793], [59.3016619, 18.0137766]
];
Shuffle the flagAreas and grab the first array.
var random = flagAreas.sort(function () { return Math.random() - 0.5 } )[0];
Add the marker.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(random[0], random[1]),
map: map,
});
}
window.onload = initialize;
Fiddle
There are 3 problems in your code.
1) Unexpected termination of the initialize without executing the for loop.
return flagAreas; //Remove this code
2)
flagAreas[i] //An array returns both lat and lng
position: new google.maps.LatLng(flagAreas[i], flagAreas[i]) //Wrong
Replace like
position: new google.maps.LatLng(flagAreas[i][0], flagAreas[i][1]) //Correct
3) Remove , whenever you reach the last option.
map: map
Finally check this in JSFiddle

How to pass multiple value to google map V3?

How to plot more number of markers in google map
<script type="text/javascript">
// When map page opens get location and display map
$('.page-map').live("pagecreate", function() {
var latt=[13.0423734,12.918907];
var lang=[80.2727993,80.145264];
for(i=0; i<latt.length;i++)
{
initialize(latt[i],lang[i]);
}
});
function initialize(lat,lng)
{
var latlng = new google.maps.LatLng(lat,lng);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"Hello World!"
});
}
</script>
Use arrays.
// When map page opens get location and display map
$('.page-map').live("pagecreate", function() {
var latt=[13.0423734,12.918907];
var lang=[80.2727993,80.145264];
initialize(latt, lang);
});
function initialize(lat_arr,lng_arr)
{
// Assuming first array element is where you want the map centered
var latlng = new google.maps.LatLng(lat_arr[0],lng_arr[0]);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
var markers = [];
// start i at 0 if you want a marker at the center as well
for(var i = 1; i < lat_arr.length; i++) {
latlng = new google.maps.LatLng(lat_arr[i], lng_arr[i]);
markers[i] = new google.maps.Marker({
position: latlng,
map: map,
title:"Hello World!"
});
}
}

Categories

Resources