How do I read a variable from another function? - javascript

In the following code, it seems that the function initialize(), once triggered by socket.on('results') is unable to read the value of "array".
block content
script.
function initialize() {
var mapOptions = {
center: { lat: -30, lng: 150},
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
setMarkers(map, array);
}
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var location = locations[i];
var myLatLng = new google.maps.LatLng(location[1], location[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: location[0]
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
div(id="map-canvas")
script.
var socket = io.connect('http://localhost:4000');
socket.on('results', function(results) {
var array = [];
results.forEach(function(item){
name = item.name;
coordinates = item.location.coordinate;
array.push([name, coordinates.latitude, coordinates.longitude]);
});
initialize();
});

Simple pass the array as a parameter when you call the initialize function.
initialize(array);
Them, in the function initialize:
function initialize(array) {REST OF THE CODE}
All code:
block content
script.
function initialize(array) {
var mapOptions = {
center: { lat: -30, lng: 150},
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
array = array || [];
setMarkers(map, array);
}
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var location = locations[i];
var myLatLng = new google.maps.LatLng(location[1], location[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: location[0]
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
div(id="map-canvas")
script.
var socket = io.connect('http://localhost:4000');
socket.on('results', function(results) {
var array = [];
results.forEach(function(item){
name = item.name;
coordinates = item.location.coordinate;
array.push([name, coordinates.latitude, coordinates.longitude]);
});
initialize(array);
});

array variable is not visible inside initialize function. It is closured in callback anonymous function. I propose to pass array as argument:
block content
script.
function initialize(array) {
var mapOptions = {
center: { lat: -30, lng: 150},
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
array = array || [];
setMarkers(map, array);
}
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var location = locations[i];
var myLatLng = new google.maps.LatLng(location[1], location[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: location[0]
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
div(id="map-canvas")
script.
var socket = io.connect('http://localhost:4000');
socket.on('results', function(results) {
var array = [];
results.forEach(function(item){
name = item.name;
coordinates = item.location.coordinate;
array.push([name, coordinates.latitude, coordinates.longitude]);
});
initialize(array);
});

Related

Cannot remove markers from google maps api

The markers in my program just wont remove with the deleteMarkers() function
CSS:
#map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
HTML:
<div style="height:500px; width:750px;">
<div id="map-canvas"></div>
</div>
<select class="form-control" name="dateSelect" id="dateSelect" onchange="dateSelect_Event();"></select>
Javascript:
var map; <--- global variables
var locations = [];
var lat_get = '';
var long_get = '';
var marker=[];
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {lat: 7.072617, lng: 125.599494},
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 13,
});
};
function deleteMarkers() {
for (var i = 0; i < marker.length; i++ ) {
marker[i].setMap(null);
}
marker.length = 0;
}
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.setMap(map);
});
}
Firebase:
-databaseName
--location
---latitude
---longitude
I just use firebase to get the lat and long on every change of the html select option and it work perfectly. The problem this time is it can't delete the markers. Should I do the deleteMarkers differently?
Thanks to #StackSlave's answer. I was able to successfully remove it by creating and pushing the google_marker to the global marker variable.
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
var google_marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
google_marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.push(google_marker);
});
marker.setMap(map);
}

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);
}

google maps Cannot read property 'maps' of undefined

i trying to display markers according to user location and i keep getting this error that as commenas it is i didnt find any solution that match my problem,
thae error i'm getiing is : Uncaught TypeError: Cannot read property 'maps' of undefined & its referring to this :at Array.filter (native) .
thanks:
<script src="https://maps.googleapis.com/maps/api/js?key="My_Api_Key"&libraries=geometry"></script>
<script>
"use strict";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
var markers = #Html.Raw(Json.Encode(Model.UpcomingLectureGigs));
var currentLatitude = position.coords.latitude;
var currentLongitude = position.coords.longitude;
var userLatLng = currentLatitude + currentLongitude;
var markersFiltered = markers.filter(function(markers, index, array, google) {
var myLatlng = new window.google.maps.LatLng(markers.Latitude, markers.Longitude);
return google.maps.geometry.spherical.computeDistanceBetween(userLatLng, myLatlng) < 10000;
});
window.onload = function(a) {
var mapOptions = {
center: new window.google.maps.LatLng(markers[0].Latitude, markers[0].Longitude),
zoom: 8,
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
var infoWindow = new window.google.maps.InfoWindow();
var map = new window.google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (var i = 0; i < markersFiltered.length; i++) {
var data = markers[i];
var myLatlng = new window.google.maps.LatLng(data.Latitude, data.Longitude);
var marker = new window.google.maps.Marker({
position: myLatlng,
draggable: true,
animation: google.maps.Animation.DROP,
get map() { return map; }
});
(function(marker, data) {
window.google.maps.event.addListener(marker,
"click",
function(e) {
infoWindow.setContent(data.Venue + " " + data.Genre.Name);
infoWindow.open(map, marker);
});
})(marker, data);
}
};
});
};
</script>
https://jsfiddle.net/1gm0u4wd/9/
Your html will be as below. Your maps api javascript will be linked inside html section not javascript section.
<div id="map" style="width: 500px; height: 500px"/>
<script src="https://maps.googleapis.com/maps/api/js?key=yourMapsAPIKey&libraries=geometry"></script>
Note : "yourMapsAPIKey" should be your API key.
You can get your maps api key from here.
Update your script as below
"use strict";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
var currentLatitude = position.coords.latitude;
var currentLongitude = position.coords.longitude;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(currentLatitude, currentLongitude),
});
//your dynamic markers
var markers = #Html.Raw(Json.Encode(Model.UpcomingLectureGigs));
//default marker at current location
//var markers = new google.maps.Marker({
//position: new google.maps.LatLng(currentLatitude, currentLongitude),
//map: map,
//title: 'Hello World!'
//});
var userLatLng = new window.google.maps.LatLng(currentLatitude, currentLongitude);
//your filter function
var markersFiltered = markers.filter(function(markers, index, array, google) {
var myLatlng = new window.google.maps.LatLng(markers.Latitude, markers.Longitude);
return google.maps.geometry.spherical.computeDistanceBetween(userLatLng, myLatlng) < 10000;
});
window.onload = function(a) {
var mapOptions = {
center: new window.google.maps.LatLng(markers[0].Latitude, markers[0].Longitude),
zoom: 8,
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
var infoWindow = new window.google.maps.InfoWindow();
var map = new window.google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (var i = 0; i < markersFiltered.length; i++) {
var data = markers[i];
var myLatlng = new window.google.maps.LatLng(data.Latitude, data.Longitude);
var marker = new window.google.maps.Marker({
position: myLatlng,
draggable: true,
animation: google.maps.Animation.DROP,
get map() {
return map;
}
});
(function(marker, data) {
window.google.maps.event.addListener(marker,
"click",
function(e) {
infoWindow.setContent(data.Venue + " " + data.Genre.Name);
infoWindow.open(map, marker);
});
})(marker, data);
}
};
});
};
Fiddle here

Adding actionListeners to dynamically created google markers to plot routes

I have a page that retrieves some locations from a database and creates markers based on their lat/long to display on a map. The markers are saved in an array and I use a for loop to assign onclick action listeners to each marker. When the user clicks on a marker I want a route from their current location to the marker location to be displayed. The issue I am having is that regardless of which marker is clicked, it always plots a route to the final marker in the array.
This is what the map looks like
In the above example I am going to click the red marker A.
As you can see it has plotted a course to marker D.
My Code:
//THIS FUNCTIONS BUILD THE MAPS
function initializeMap(position)
{ //USER LOCATION
var myCenter = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapProp =
{
center: myCenter,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapObj = new google.maps.Map(document.getElementById("googleMap"), mapProp);
//MAKING SURE THE DATA ARRAY HAS SOMETHING IN IT
if (ajaxResult.length > 0)
{
for (var i = 0; i < ajaxResult.length; i++)
{
var pos = {lat: parseFloat(ajaxResult[i][6]), lng: parseFloat(ajaxResult[i][7])};
//BUILDING THE DESTINATION MARKERS
var suggestionMarker = new google.maps.Marker({
position: pos,
icon: markerNames[i]
});
markers.push(suggestionMarker);//ADDING TO THE MARKER ARRAY
suggestionMarker.setMap(mapObj);//ADING TO THE MAP
var userString = ajaxResult[i][1];//INFORMATINO WINDOW
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, suggestionMarker);
}
addMarkerListeners(myCenter);
}
//MARKER FOR THE USER LOCATION
var userImage = 'assets/img/GoogleMapsMarkers/blue_MarkerA.png'
var userMarker = new google.maps.Marker({
position: myCenter,
icon: userImage
});
markers.push(userMarker);
userMarker.setMap(mapObj);
//USER INFORMATION WINDOW
var userString = "You!";
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, userMarker);
}
/*
*
* #param {type} option
* #returns {Boolean}
* ACCEPTS THE USER LOCATION AND ADDS ACTION LISTENERS TO EACH MARKER
* IN THE MARKER ARRAY. THE ACTION LISTENER CALLS THE PLOT ROUTE
* FUNCTION AND PASSES IT THE MARKER POSITION AND USER POSITION
*/
function addMarkerListeners(myCenter)
{
if(markers.length > 0)
{
for(var i = 0; i < markers.length-1; i++)
{
google.maps.event.addListener(markers[i],'click', function(){plotRoute(markers[i].getPosition(),myCenter);});
//markers[i].addEventListener('click', function(){plotRoute(markers[i].getPosition(),myCenter);});
directionsDisplay.setMap(mapObj);
}
}
}
//CREATES A ROUT
function plotRoute(pos, myCenter)
{
var request = {
origin: myCenter,
destination: pos,
travelMode: 'DRIVING'
};
directionsService.route(request, function(result,status){
if(status === 'OK')
{
directionsDisplay.setDirections(result);
}
});
}
Note that the actual final marker is always the user marker but the for loop is instructed not to include it. Can anyone see why it only ever plots a route to the final destination marker in the marker array?
This is a common problem with loops setting up event listeners. It is solved in this related question: Google Maps JS API v3 - Simple Multiple Marker Example using function closure. To use that solution in your code:
function addMarkerListeners(myCenter) {
if (markers.length > 0) {
for (var i = 0; i < markers.length; i++) {
// function closure on the "i" variable
google.maps.event.addListener(markers[i], 'click', (function(i) {
return function() {
plotRoute(markers[i].getPosition(), myCenter);
}})(i));
directionsDisplay.setMap(mapObj);
}
}
}
proof of concept fiddle
To solve it without function closure, you could use the this inside the event handler function, which refers to the marker clicked:
function addMarkerListeners(myCenter) {
if (markers.length > 0) {
for (var i = 0; i < markers.length; i++) {
google.maps.event.addListener(markers[i], 'click', function() {
plotRoute(this.getPosition(), myCenter);
});
directionsDisplay.setMap(mapObj);
}
}
}
proof of concept fiddle
code snippet (using function closure):
var geocoder;
var map;
var markers = [];
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
function initialize() {
// Googleplex 37.4223434, -122.0843689
var position = {coords: {latitude:37.4223434, longitude:-122.0843689}}
initializeMap(position);
}
google.maps.event.addDomListener(window, "load", initialize);
// Menlo Park, CA, USA (37.4529598, -122.18172520000002)
// Mountain View, CA, USA (37.3860517, -122.0838511)
var ajaxResult = [[0,"infowindow 0",2,3,4,5,37.4419,-122.1419],
[1,"infowindow 1",2,3,4,5,37.4529598,-122.1817252],[2,"infowindow 2",2,3,4,5,37.3860517,-122.0838511]]
//THIS FUNCTIONS BUILD THE MAPS
function initializeMap(position) { //USER LOCATION
var myCenter = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapProp = {
center: myCenter,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapObj = new google.maps.Map(document.getElementById("googleMap"), mapProp);
//MAKING SURE THE DATA ARRAY HAS SOMETHING IN IT
if (ajaxResult.length > 0) {
for (var i = 0; i < ajaxResult.length; i++) {
var pos = {
lat: parseFloat(ajaxResult[i][6]),
lng: parseFloat(ajaxResult[i][7])
};
//BUILDING THE DESTINATION MARKERS
var suggestionMarker = new google.maps.Marker({
position: pos,
// icon: markerNames[i]
});
markers.push(suggestionMarker); //ADDING TO THE MARKER ARRAY
suggestionMarker.setMap(mapObj); //ADING TO THE MAP
var userString = ajaxResult[i][1]; //INFORMATINO WINDOW
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, suggestionMarker);
}
addMarkerListeners(myCenter);
}
//MARKER FOR THE USER LOCATION
var userImage = 'http://maps.google.com/mapfiles/ms/micons/blue.png'
var userMarker = new google.maps.Marker({
position: myCenter,
icon: userImage
});
markers.push(userMarker);
userMarker.setMap(mapObj);
//USER INFORMATION WINDOW
var userString = "You!";
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, userMarker);
}
/*
*
* #param {type} option
* #returns {Boolean}
* ACCEPTS THE USER LOCATION AND ADDS ACTION LISTENERS TO EACH MARKER
* IN THE MARKER ARRAY. THE ACTION LISTENER CALLS THE PLOT ROUTE
* FUNCTION AND PASSES IT THE MARKER POSITION AND USER POSITION
*/
function addMarkerListeners(myCenter) {
if (markers.length > 0) {
for (var i = 0; i < markers.length; i++) {
google.maps.event.addListener(markers[i], 'click', (function(i) {
return function() {
plotRoute(markers[i].getPosition(), myCenter);
}})(i));
directionsDisplay.setMap(mapObj);
}
}
}
//CREATES A ROUTE
function plotRoute(pos, myCenter) {
var request = {
origin: myCenter,
destination: pos,
travelMode: 'DRIVING'
};
directionsService.route(request, function(result, status) {
if (status === 'OK') {
directionsDisplay.setDirections(result);
} else alert("directions request failed: "+status);
});
}
html,
body,
#googleMap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googleMap"></div>
code snippet (using this):
var geocoder;
var map;
var markers = [];
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
function initialize() {
// Googleplex 37.4223434, -122.0843689
var position = {coords: {latitude:37.4223434, longitude:-122.0843689}}
initializeMap(position);
}
google.maps.event.addDomListener(window, "load", initialize);
// Menlo Park, CA, USA (37.4529598, -122.18172520000002)
// Mountain View, CA, USA (37.3860517, -122.0838511)
var ajaxResult = [[0,"infowindow 0",2,3,4,5,37.4419,-122.1419],
[1,"infowindow 1",2,3,4,5,37.4529598,-122.1817252],[2,"infowindow 2",2,3,4,5,37.3860517,-122.0838511]]
//THIS FUNCTIONS BUILD THE MAPS
function initializeMap(position) { //USER LOCATION
var myCenter = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapProp = {
center: myCenter,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapObj = new google.maps.Map(document.getElementById("googleMap"), mapProp);
//MAKING SURE THE DATA ARRAY HAS SOMETHING IN IT
if (ajaxResult.length > 0) {
for (var i = 0; i < ajaxResult.length; i++) {
var pos = {
lat: parseFloat(ajaxResult[i][6]),
lng: parseFloat(ajaxResult[i][7])
};
//BUILDING THE DESTINATION MARKERS
var suggestionMarker = new google.maps.Marker({
position: pos,
// icon: markerNames[i]
});
markers.push(suggestionMarker); //ADDING TO THE MARKER ARRAY
suggestionMarker.setMap(mapObj); //ADING TO THE MAP
var userString = ajaxResult[i][1]; //INFORMATINO WINDOW
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, suggestionMarker);
}
addMarkerListeners(myCenter);
}
//MARKER FOR THE USER LOCATION
var userImage = 'http://maps.google.com/mapfiles/ms/micons/blue.png'
var userMarker = new google.maps.Marker({
position: myCenter,
icon: userImage
});
markers.push(userMarker);
userMarker.setMap(mapObj);
//USER INFORMATION WINDOW
var userString = "You!";
var infowindow = new google.maps.InfoWindow({
content: userString
});
infowindow.open(mapObj, userMarker);
}
/*
*
* #param {type} option
* #returns {Boolean}
* ACCEPTS THE USER LOCATION AND ADDS ACTION LISTENERS TO EACH MARKER
* IN THE MARKER ARRAY. THE ACTION LISTENER CALLS THE PLOT ROUTE
* FUNCTION AND PASSES IT THE MARKER POSITION AND USER POSITION
*/
function addMarkerListeners(myCenter) {
if (markers.length > 0) {
for (var i = 0; i < markers.length; i++) {
google.maps.event.addListener(markers[i], 'click', function() {
plotRoute(this.getPosition(), myCenter);
});
directionsDisplay.setMap(mapObj);
}
}
}
//CREATES A ROUT
function plotRoute(pos, myCenter) {
var request = {
origin: myCenter,
destination: pos,
travelMode: 'DRIVING'
};
directionsService.route(request, function(result, status) {
if (status === 'OK') {
directionsDisplay.setDirections(result);
}
});
}
html,
body,
#googleMap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googleMap"></div>

Display multiple markers, variable and array problems

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>

Categories

Resources