Javascript variable loop - javascript

I need to assign 50 map markers for a google map. I don't want to have the (almost) same line of code 50 times. What is the best way to loop through this easily and optimize code?
var marker1 = new google.maps.Marker({position: new google.maps.LatLng(location1_latitude,location1_longitude),map: map1,title:location1});
var marker2 = new google.maps.Marker({position: new google.maps.LatLng(location2_latitude,location2_longitude),map: map1,title:location2});
var marker3 = ...
repeating to
var marker50 = new google.maps.Marker({position: new google.maps.LatLng(location50_latitude,location50_longitude),map: map1,title:location50});

you can use two arrays and iterate over them:
var location_latitude = [0,1,2,3,4,5] // all your latitudes
var location_longitude = [0,1,2,3,4,5] // all your longitudes
var location_titles = ['loc0','loc1','loc2','loc3','loc4','loc5']
var markers = []
for (var i = 0; i < location_latitude.length && i < location_longitude.length && i < location_titles.length; i++) {
markers[i] = new google.maps.Marker({position: new google.maps.LatLng(location_latitude[i],location_longitude[0]),map: map1,title:location_titles[i]});
}
you can also abstract lat, lng and title into an object:
var locations = [{lat: 0, lng: 0, title: 'latlng0'},{lat: 0, lng: 0, title: 'latlng0'}] // depending on how you get you're data, you'll want to adjust your loop's format so you don't have to manually convert it
var markers = []
for (var i = 0; i < locations.length; i++) {
var current = locations[i]
markers[i] = new google.maps.Marker({position: new google.maps.LatLng(current.lat,current.lng),map: map1,title:current.title});
}

Related

method fitBounds() only zooms to single marker

I have rendered a map with markers, which are saved as long lat values in a local xlsx file.
My aim is to automatically zoom to all markers, which are loaded via an input file button. For this I am using the fitbounds() method from googlemaps API.
Partial Example
function handleFile(e) {
//Get the files from Upload control
var files = e.target.files;
var i, f;
//Loop through files
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
var data = e.target.result;
var result;
var workbook = XLSX.read(data, { type: 'binary' });
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) { /* iterate through sheets */
//Convert the cell value to Json
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
if (roa.length > 0) {
result = roa;
}
});
//create global infoWindow object
var infoWindow = new google.maps.InfoWindow();
var i, newMarker;
var gmarkers = [];
//loop over json format
for (i = 0, length = result.length; i < length; i++) {
var data = result[i];
//extract Lat Long values from result
latLng = new google.maps.LatLng(data.Latitude, data.Longitude);
//creating a marker and putting it on the map
newMarker = new google.maps.Marker({
position: latLng,
map: map
});
gmarkers.push(newMarker);
}
for (var i=0; i < gmarkers.length; i++) {
bounds = new google.maps.LatLngBounds();
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
}
}
}
};
reader.readAsArrayBuffer(f);
}
But if I run my html file, it zooms just to one marker. I suppose that it is the first marker of the gmarkers array.
However I want to achieve following result, with the full extent of my uploaded marker:
In my main.html you can see my initMap() function and the function which is called if the document is ready. In the document ready function the handlefunction () is called.
var map;
//Change event to dropdownlist
$(document).ready(function(){
a = $('#input-id').fileinput({
'showUpload': false,
'showPreview': false,
'showCaption': false
});
a.change(handleFile);
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 48.7758459, lng: 9.1829321},
zoom: 3,
mapTypeControl: false
});
}
You have a typo in your code. Move the initialization of the bounds outside the loop.
for (var i=0; i < gmarkers.length; i++) {
bounds = new google.maps.LatLngBounds();
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
should be:
bounds = new google.maps.LatLngBounds();
for (var i=0; i < gmarkers.length; i++) {
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
proof of concept fiddle
code snippet:
var result = [{
Latitude: 37.4419,
Longitude: -122.1419
}, {
Latitude: 37.44,
Longitude: -122.14
}, {
Latitude: 40.44,
Longitude: -75.14
}]
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var gmarkers = [];
//loop over json format
for (i = 0, length = result.length; i < length; i++) {
var data = result[i];
//extract Lat Long values from result
latLng = new google.maps.LatLng(data.Latitude, data.Longitude);
//creating a marker and putting it on the map
newMarker = new google.maps.Marker({
position: latLng,
map: map
});
gmarkers.push(newMarker);
}
bounds = new google.maps.LatLngBounds();
for (var i = 0; i < gmarkers.length; i++) {
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
This is another approach for your problem within 35 lines of code.
Make sure you pass the JSON object the right way and that you declare your classes within the appropriate lexical scope.
Make sure the JSON Object returns something like this:
const coords = [
{lat: 42.4, lng: 1.55},
{lat: 43.42, lng: 2.48},
{lat: 45.43, lng: 4.9}
];
Note I have changed result to a more meaningful coords array of objects.
// Create your markers without worrying about scope and without extensive For Loops
const markers = coords.map((coord) => {
return new google.maps.Marker({
position: new google.maps.LatLng(coord.lat, coord.lng),
map: map,
animation: google.maps.Animation.DROP
});
})
// Declare your bounds outside the map method (previous for loop)
const bounds = new google.maps.LatLngBounds();
// Iterate through markers and return coords for expanded viewport
markers.forEach((loc) =>{
loc = new google.maps.LatLng(loc.position.lat(), loc.position.lng());
return bounds.extend(loc);
});
map.fitBounds(bounds);
}

For loop through Array only shows last value, Google Map

I'm trying to place 3 markers on Google Map.
In JavaScript I wrote my loop as below
var places = ["Bondi Beach", "Coogee Beach", "Cronulla Beach"];
var lat = [-33.890542, -33.923036, -34.028249];
var lng = [151.274856, 151.259052, 151.157507];
var z=0;
for (tot=lat.length; z < tot; z++) {
var locations = [
[places[z], lat[z], lng[z]]
];
}
Then I initialized my map
var map;
var markers = [];
function init(){
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var num_markers = locations.length;
for (var i = 0; i < num_markers; i++) {
markers[i] = new google.maps.Marker({
position: {lat:locations[i][1], lng:locations[i][2]},
map: map,
html: locations[i][0],
id: i,
});
google.maps.event.addListener(markers[i], 'click', function(){
var infowindow = new google.maps.InfoWindow({
id: this.id,
content:this.html,
position:this.getPosition()
});
google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){
markers[this.id].setVisible(true);
});
this.setVisible(false);
infowindow.open(map);
});
}
}
init();
However this output only one marker (the last one), I'm wondering what is wrong with my loop?
for (tot=lat.length; z < tot; z++) {
var locations = [
[places[z], lat[z], lng[z]]
];
}
Here you're overwriting the locations array with every iteration.
Push the new elements into the array instead.
var locations = []
for (tot=lat.length; z < tot; z++) {
locations.push([places[z], lat[z], lng[z]]);
}

Function fails to delete markers from a Google Map

The function below does not remove the markers when called. Why?
// Remove existing markers from the Map
function removeMarkers(markersArray) {
var j,position;
for (j = 0; j < markersArray.length; j += 1){
position = new google.maps.Marker({
position: {lat: markersArray[j][1], lng: markersArray[j][2]}
});
position.setMap(null);
};
};
Here is the array that is being fed into the function:
var educationMarkers = [
['Grafton Campus, Auckland University', -36.861717, 174.769424],
["Auckland Boys' Grammar", -36.872432, 174.768126],
["Epsom Girls' Grammar", -36.876177, 174.773639],
["St. Peter's College", -36.868412, 174.768575],
["ACG Parnell College", -36.863163, 174.778555],
["Newmarket Campus, Auckland University", -36.865905, 174.7733]
];
You need to keep reference of the markers you placed.
var placedMarkers = [];
function placeMarkers(markersArray) {
var marker, i, postiion, bounds = new google.maps.LatLngBounds();
for (i = 0; i < markersArray.length; i += 1) {
marker = new google.maps.Marker({
map: map,
position: {
lat: markersArray[i][1],
lng: markersArray[i][2]
}
});
// keep reference of the markers you placed
placedMarkers.push(marker);
position = new google.maps.LatLng(markersArray[i][1], markersArray[i][2]);
bounds.extend(position);
}
map.fitBounds(bounds);
};
and when removing the markers, use the reference array you kept.
// Remove existing markers from the Map
function removeMarkers() {
var j,position;
// loop through reference array you kept.
for (j = 0; j < placedMarkers.length; j += 1){
placedMarkers[j].setMap(null);
};
};
If the markers in the loop are correct,Just change your for loop with this,Make a fiddler if possible
for (j = 0; j < markersArray.length; j += 1){
position[j] = new google.maps.Marker({
position: {lat: markersArray[j][1], lng: markersArray[j][2]}
});
position[j].setMap(null);
};

Why i dont have marker in Google map API

I am a beginner to HTML and JavaScript . I read a text file which contains longitude and Latitude.
I read that text file and store it in 3 arrays. One contains longitude, One latitude and one contains ID.
Text file is like this: (you can store it for debugging purpose with my code below)
ID LONGITUDE LATITUDE
0 77.139305 28.795975
2 77.308929 28.486877
4 73.820680 18.464110
6 75.588783 26.599820
12 77.193575 28.559693
I read it and stored the column 1 , 2 and in col1, col2, col3 respectively.
Now the problem is the code below show me the marker on map only when I put the long lat manually but when I use the my column arrays it don't show me any marker whereas it shows map.
What i have in mind is to run this for loop in my code and it should render all the marker in the given map.(Yes it's true that i have stored all the Long and Lat and Id i can see on debugging).
My code is :
for (var i = 0; i <= array.length - 1; i++)
{
col1[j] = array[i];
col2[j] = array[i + 1];
col3[j] = array[i + 2];
var myLatlng = new google.maps.LatLng(col3[j], col2[j]);
var mapOptions =
{
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
j++;
};
There are multiple things wrong with your code...
The map is declared inside the loop
Your split does not work correctly
The increments on your arrays to not step enough i
The Latitude and Longitude's were backwards in the marker definition
I have made the following edits and have a fiddle for you to look at so you can merge the code... http://jsfiddle.net/b4fz30vc/
function initialize() {
var data =
"ID LONGITUDE LATITUDE\r\n" +
"0 77.139305 28.795975\r\n" +
"2 77.308929 28.486877\r\n" +
"4 73.820680 18.464110\r\n" +
"6 75.588783 26.599820\r\n" +
"12 77.193575 28.559693\r\n";
var s2 = data.replace(/^.*$/, "").replace(/\r\n/g, " ");
var array = s2.split(/[ ]+/g);
var col1 = [];
var col2 = [];
var col3 = [];
var j = 0;
var mapOptions = {
zoom: 2,
center: new google.maps.LatLng(73, 23)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (var i = 0; i <= array.length - 1; i++) {
col1[j] = array[i];
col2[j] = array[i++];
col3[j] = array[i++];
var myLatlng = new google.maps.LatLng(col3[j], col2[j]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World! ' + col1[j]
});
j++;
}
}
initialize();
EDIT:
To comment on the var s2 = data.replace(/^.*$/, "").replace(/\r\n/g, " "); line.. with the first replace I am removing the header row and the second one removes the new lines.
You have to create a Marker array
var markers[];
Then in the loop you have to create to iterate over lat/longs, after marker is created put it into the array:
markers.push(marker);
In this way you can keep markers active...
You create new map for every marker, so your output contains only the last map with the last marker. Try to move this code:
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
before the for loop
btw in your for loop you should increment your iterator by 3

javascript loop for taking data from XML

I have this JavaScript which should loop through my XML and get my data.
Here is the javascript code I have:
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
var line =[];
downloadUrl("exportintoxml2.php", function(data) {
var xml = data.responseXML;
var devs = xml.documentElement.getElementsByTagName("DEVS"),
data = {};
for (var n = 0; n < devs.length; n++) {
var dev = devs[n],
markers = dev.getElementsByTagName("marker"),
dev_id = dev.getAttribute('DEVS');
data[dev_id] = [];
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("USER");
var imei = markers[i].getAttribute("IMEI");
var gsm1 = markers[i].getAttribute("GSM1");
var devices = markers[i].getAttribute("DEVS");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("LAT")),
parseFloat(markers[i].getAttribute("LON")));
var html = "<b>" + name + "</b> <br/>" + imei;
var icon = customIcons[devices] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
data[dev_id].push = ({ 'point' : point });
line.push(data[1]);
}
}
map.setCenter(point, 16);
var polyline = new google.maps.Polyline({
path: line,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
polyline.setMap(map);
});
}
I need a variable (or several variables) which contains all of the data for every DEV separately and I am not sure how to include it in this loop.
I need to be able to display different devices with different polylines without them being connected with each other.
How can this be solved?
You need a loop for devs.
var devs = xml.documentElement.getElementsByTagName("DEVS"),
data = {}; // for storing the data after extraction
for ( var n = 0; n < devs.length; n++ ) {
var dev = devs[n],
markers = dev.getElementsByTagName("marker"),
dev_id = dev.getAttribute('devs');
data[dev_id] = [];
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("USER");
var data1 = markers[i].getAttribute("DATA1");
var data2 = markers[i].getAttribute("DATA2");
var devs2 = markers[i].getAttribute("DEVS");
data[dev_id].push({ 'name': name, 'data1': data1, 'data2': data2, 'devs': devs2 }); // store the data
}
}
In the line:
> var dev1 =
> xml.documentElement.getElementsByTagName("DEVS")[0];
getElementsByTagName returns a live NodeList. If you change it to:
var devs = xml.documentElement.getElementsByTagName("DEVS");
you can now loop over all the DEVS elements in the document.
As for storage of all the values, you already have them in the XML document so you might consider a function that returns the values as you need them, or get them all in a loop and store them in an object (but then you likely have to loop over the objet to get them back, just like you did in the first place to put them in there).

Categories

Resources