I try to display multiple markers on my map. I put the multiples location in adata-attribute trough my php file. Then I try to grab this information in my javascript one.
If I directly paste the coordinates, the markers appear. If I reference the data-attribute they don't. (The only difference is on the line beginning with var locations.)
This code works:
function GoogleMapsInit(){
setTimeout(function initialize() {
var emplacements = $('#iframecarte').attr("data-emplacements");
// Emplacements returns [[45.5314817,-73.1835154], [45.570004,-73.448701] ]
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(45.5580421, -73.7303025)
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var locations = [[45.5314817,-73.1835154], [45.570004,-73.448701] ];
var marker, i;
var markers = new Array();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
markers.push(marker);
}
}, 500);
}
This one doesn't:
function GoogleMapsInit(){
setTimeout(function initialize() {
var emplacements = $('#iframecarte').attr("data-emplacements");
// Emplacements returns [[45.5314817,-73.1835154], [45.570004,-73.448701] ]
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(45.5580421, -73.7303025)
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var locations = emplacements;
var marker, i;
var markers = new Array();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
markers.push(marker);
}
}, 500);
}
What is wrong with the variable locations when it references the emplacements variable so that the markers don't show?
The non-working version emplacements is a string, not an array.
Convert the string to a javascript array:
var locations = JSON.parse(emplacements);
proof of concept fiddle
code snippet:
function GoogleMapsInit() {
setTimeout(function initialize() {
var emplacements = $('#iframecarte').attr("data-emplacements");
// Emplacements returns [[45.5314817,-73.1835154], [45.570004,-73.448701] ]
var mapOptions = {
zoom: 9,
center: new google.maps.LatLng(45.5580421, -73.7303025)
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var locations = JSON.parse(emplacements);
var marker, i;
var markers = new Array();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
markers.push(marker);
}
}, 500);
}
GoogleMapsInit();
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
<div id="iframecarte" data-emplacements="[[45.5314817,-73.1835154], [45.570004,-73.448701], [45.6066487,-73.712409]]"></div>
Related
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);
}
I am using google maps API to make some custom markers and i want to open a custom info window. I have been trying to set the position of the info window but its always opening on the extreme top left.
var markers = [
[37.09024, -95.712891, "images/white-star.png"],
[40.4173, -82.9071, "images/purple-star.png"],
[31.9686, -99.9018, "images/yellow-star.png"],
];
for (i = 0; i < markers.length; i++) {
var position = new google.maps.LatLng(markers[i][0], markers[i][1]);
var icon = markers[i][2];
marker[i] = infowindow = new google.maps.InfoWindow({
content: html,
pixelOffset: new google.maps.Size(200, 0)
});
marker[i] = new google.maps.Marker({
position: position,
icon: icon,
map: map,
}).addListener('mouseover', function() {
infowindow.open(map, marker[i]);
});
}
I think your problem lies how to create marker and info window in your code.To create multiple markers in map, see code below .
Fiddle demo
function initMap() {
var myLatLng = {
lat: 40.4173,
lng: -82.9071
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var markers = [
[37.09024, -95.712891, "images/white-star.png"],
[40.4173, -82.9071, "images/purple-star.png"],
[31.9686, -99.9018, "images/yellow-star.png"],
];
for (i = 0; i < markers.length; i++) {
(function(markers) {
var position = new google.maps.LatLng(markers[0], markers[1]);
var icon = markers[2];
var infowindow = new google.maps.InfoWindow({
content: 'html',
pixelOffset: new google.maps.Size(200, 0)
});
var markerss = new google.maps.Marker({
position: position,
map: map,
//icon: icon,
});
google.maps.event.addListener(markerss, 'click', function() {
infowindow.open(map, markerss);
});
})(markers[i]);
}
}
marker[i] is not defined in this line:
infowindow.open(map, marker[i]);
Without a defined anchor, the infowindow ends up in the upper left hand corner of the map.
You can use this for the anchor in the mouseover event handler function:
infowindow.open(map, this);
You probably also want to remove the:
pixelOffset: new google.maps.Size(200, 0)
proof of concept fiddle
code snippet:
var geocoder;
var map;
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 markers = [
[37.09024, -95.712891, "images/white-star.png"],
[40.4173, -82.9071, "images/purple-star.png"],
[31.9686, -99.9018, "images/yellow-star.png"],
];
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var html = "marker";
var position = new google.maps.LatLng(markers[i][0], markers[i][1]);
var icon = markers[i][2];
var infowindow = new google.maps.InfoWindow({
content: html,
// pixelOffset: new google.maps.Size(200, 0)
});
var marker = new google.maps.Marker({
position: position,
// icon: icon,
map: map,
}).addListener('mouseover', function() {
infowindow.open(map, this);
});
bounds.extend(position);
}
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 line is not working and no error in console.
position: new google.maps.LatLng( coordsArray[i].location ),
data confirmed by alert(coordsArray[i].location);location been database field returning LatLng -43.59670,172.38247 as a string.
This line works: position: new google.maps.LatLng( -43.59670,172.38247 ),
What is the same data as above, any ideas what wrong with my code?
var list_location = localStorage.getItem('myHouse');
var obj = JSON.parse(list_location);
var coordsArray = obj;
var marker;
var locX;
var image = 'http://apppics.weebly.com....png';
var map = Appery("googlemap_6").options.mapElement.gmap('get', 'map');
var CreateMarker = function(coordsArray, i){
var marker = new google.maps.Marker({
position: new google.maps.LatLng( coordsArray[i].location ),
//position: new google.maps.LatLng( -43.59670,172.38247 ),
title: coordsArray[i].storeName,
map: Appery("googlemap_6").gmap,
});
for (var i = 0, j = coordsArray.length; i < j-1; i++)
alert(coordsArray[i].location);
CreateMarker(coordsArray, i);
This is incorrect: new google.maps.LatLng(coordsArray[i].location).
You state: "location been database field returning LatLng -43.59670,172.38247 as a string."
the google.maps.LatLng constructor takes two numbers as arguments (not a comma separated string).
If coordsArray[i].location is a comma separated string, convert it to two numbers.
var coords = coordsArray[i].location.split(",");
var latLng = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
var marker = new google.maps.Marker({
position: latLng,
map: map
});
code snippet:
var geocoder;
var map;
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 location = "-43.59670,172.38247";
coords = location.split(",");
var latLng = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
var marker = new google.maps.Marker({
position: latLng,
map: map
});
map.setCenter(latLng);
}
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>
i was trying to use google map api v3 and pop up some markers on the map. un fortunately it doesnt show up on my map. i use array push to store marker with latitude and longitude parameter.
here is my code
<script type="text/javascript">
var trackerMarkerArray = [];
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var myLatlng2 = new google.maps.LatLng(-25.363800,131.044900);
var mapOptions = {
center: myLatlng,
zoom: 8
};
try {
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var marker = new google.maps.Marker({
position: myLatlng
});
var marker2 = new google.maps.Marker({
position: myLatlng2
});
trackerMarkerArray.push(marker);
trackerMarkerArray.push(marker2);
for (var i = 0; i<trackerMarkerArray.lenght; i++){
trackerMarkerArray[i].setMap(map);
console.log("value" + trackerMarkerArray[i]);
}
} catch (err){
alert(err);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
for (var i = 0; i<trackerMarkerArray.lenght; i++)
lenght must be "length"
also, when the map is not showing, try to see browser's debug console for any error.
The map comes up and the point appears. I have the title appearing as well. But as soon as I click on the marker to get info, nothing appears. Firebug info is below.
The information is being brought in via a database and there are multiple items; multiple markers are shown on the map as they should.
Any help would be apprecaited. Thanks..
Firebug Point Info:
MarkLat[i] = xx.xxxxxxxxxxxxxx;
MarkLong[i] = -xx.xxxxxxxxxxxxxx;
MarkerTitle[i] = 'Title 1';
Display[i] = '<table><tr><td>Title 1</td></tr><tr><td>Title 1 Address<br />Title 1 City, State Zip</td></tr><tr><td>Title 1 Phone</td></tr><tr><td>Title 1 Email</td></tr><tr><td>Title 1 URL</td></tr></table>';
Firebug Error:
infowindow is not defined
infowindow.open(map,marker);
Code:
<script type="text/javascript">
var i = -1;
var MarkLat=new Array();
var MarkLong=new Array();
var MarkerTitle=new Array();
var Display=new Array();
var MapCenter = new google.maps.LatLng(xx.xxxxxxxxxxxxxx,-xx.xxxxxxxxxxxxxx)
</script>
<script type="text/javascript">
var i = i + 1;
MarkLat[i] = [[Lat]];
MarkLong[i] = [[Long]];
MarkerTitle[i] = '[[Title]]';
Display[i] = '<table><tr><td>[[Title]]</td></tr><tr><td>[[Address]]<br />[[City]], [[State]] [[Zip]]</td></tr><tr><td>[[Phone]]</td></tr><tr><td>[[Email]]</td></tr><tr><td>[[WebURL]]</td></tr></table>';
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var myOptions = {
zoom: 12,
center: MapCenter,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT,
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
for (var i = 0, length = 50; i < length; i++) {
var latLng = new google.maps.LatLng(MarkLat[i],MarkLong[i]);
var infoWindow = new google.maps.InfoWindow(Display[i]);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: MarkerTitle[i]
});
google.maps.event.addDomListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Changing to a capital W was not enough for me. Only one location was being opened. I tested your code with two points:
MarkLat = [];
MarkLong = [];
Display = [];
MarkerTitle= [];
MarkLat[0] = 0;
MarkLong[0] = 0;
Display[0] = { content: "hi" };
MarkerTitle[0] = "hello";
MarkLat[1] = 10;
MarkLong[1] = 10;
Display[1] = { content: "hi 2" };
MarkerTitle[1] = "hello 2";
I'm guessing you only want one InfoWindow on the screen at any given time. Then, a single InfoWindow should be declared, with the contents kept inside the marker, and have the contents change as the marker is clicked.
var infoWindow = new google.maps.InfoWindow();
for (var i = 0, length = Display.length; i < length; i++) {
var latLng = new google.maps.LatLng(MarkLat[i],MarkLong[i]);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: MarkerTitle[i],
infoWindowContent: Display[i]
});
// Notice I used the 'this' keyword inside the listener
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(this.infoWindowContent.content);
infoWindow.open(map,this);
});
}
The alternative, having many InfoWindows pop up, needs a change to click listener, so that a reference to each individual InfoWindow is preserved. This effect is accomplished with an anonymous function wrapped around the infoWindow.open function (a new function scope is created).
for (var i = 0, length = Display.length; i < length; i++) {
var latLng = new google.maps.LatLng(MarkLat[i],MarkLong[i]);
var infoWindow = new google.maps.InfoWindow(Display[i]);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: MarkerTitle[i]
});
google.maps.event.addListener(marker, 'click', (function(infoWindow) {
return function() {
infoWindow.open(map,this);
}
})(infoWindow));
}
infowindow != infoWindow
You just have declared it with a capital, trying to use it without