New to javascript. Trying to add a list of markers (from python) to a google map.
My raw Jinja2 template:
<head>
<title>Google Map Test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
#map-canvas { height: 700px; width: 400px; }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&sensor=false">
</script>
<script type="text/javascript">
var locations = {{ locations|safe }};
/*
locations|safe results in the following line in my rendered template:
var locations = [['A.W. Hastings / Windows & Doors by Brownell', '44.4456', '-73.1276'], ['AARP', '44.4757', '-73.2113'], ['Adirondack Audiology', '44.4792', '-73.22'], ['Alchemy Jewelry Arts #1A', '44.4672', '-73.2147'], ['All Smiles Dental', '44.2334', '-72.5539']];
*/
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(43.953, -72.593),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (var i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
I send the list "locations" from my view because the list changes regularly.
I am receiving the Uncaught Reference Error for the line where I define the locations variable. The full output is:
Uncaught ReferenceError: None is not defined 127.0.0.1:14
(anonymous function)
Move the code that follows the function initialize() inside the function, otherwise the variable map is not available when and where you access it.
Related
I have this code for a map of the Smithsonian air and space museum, and the map on Google has multi floors available and a selector that allows you to switch between them.
Is there a way to have this selector show up on my map?
code:
edit: Older post doesn't solve my issue, has google updated v3 for this yet?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?key=AIzaSyARP6gVN4t8LL9pD-KtM3DCJbxWY4KSUUY&sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 600px; height: 600px;"></div>
<script type="text/javascript">
var locations = [
['Smithsonian National Air and Space Museum', 38.88815, -77.01985],
['Lockheed Martin IMAX Theater', 38.888342, -77.019492]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: new google.maps.LatLng(38.88758,-77.01998),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon:'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='+ (i + 1) +'|50C9F8|000000',
shadow:'https://chart.googleapis.com/chart?chst=d_map_pin_shadow'
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
The ultimate goal is to be able to have markers set on multiple floors, and I would like to implement this into my existing code if possible.
I'm trying to combine the following two blocks of codes together.
but for some reason, when i load the page in the browser, First the second blocks of code loads the marker on the map and then the page refreshes and the first blocks of code loads on the map!
This is my entire code:
<!DOCTYPE html>
<html>
<head>
<title>Google maps</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
geocoder = new google.maps.Geocoder();
function initialize() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
codeAddress();
}
function codeAddress() {
var address = '<?= $_GET['location'] ?>';
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
icon: 'meicon.png',
map: map,
position: results[0].geometry.location
});
} else {
alert("Error loading map");
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<script type="text/javascript">
var locations = [
['Bondi Beach', 51.5033631,-0.1276253, 1]
];
var maps = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 15,
center: new google.maps.LatLng(51.5033630,-0.1276250),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var markers, i;
for (i = 0; i < locations.length; i++) {
markers = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: maps
});
google.maps.event.addListener(markers, 'click', (function(markers, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, markers);
}
})(markers, i));
}
</script>
</body>
</html>
could someone please advise on this issue?
Thanks in advance.
It's probably because you're calling the geocoder on the address in the first block, which is an async call to google to check the address. While the code is talking to google the page runs the second code block. When that call returns it runs the rest of the code in the first block, which sets the center of the map.
The reason is simple you are loading two map the first called in <head> script what build a map in map-canvas named map. the second in body script you create another map named maps and this too create in map-canvas.You need only a working map and with this do what you nedd.
I would like to ask you a solution for this problem.
I have a JS with a variable inside that is updated overtime by a JAVA application (i.e. JAVA writer into a thread), after that I take the coordinates from that variable and I create a new object Marker for my google maps. The problem is that the marker does not changes position, it changes only if I refresh the whole page (I dont want to do this).
Here's the code to be more clear.
The inputData.js where the variable is written by the java application
var newMarker = {'latitude':38.25705300000004,'longitude': 140.83760400000006};
my html page used to display the map
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MYKEY">
</script>
<script type="text/javascript" src="inputData.js"></script>
<script>
var map;
var sendai = new google.maps.LatLng(38.259535, 140.846816);
var lastPosition;
var image = 'images/circle-16.png';
function initialize() {
var mapOptions = {
zoom: 12,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
setInterval(refreshData, 2000);
function refreshData() {
var marker = new google.maps.Marker({
map: map,
icon: image,
draggable: false
});
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
If I open my page like this everything work but when I change the script "inputData.js" the marker does not changes position.
The method setCenter on the other hand seems to work properly.
Help me please!
You'll need to reload the updated script to get the updated position:
function initialize() {
var mapOptions = {
zoom: 18,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP},
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions),
//we will store the LatLng here
pos = new google.maps.MVCObject(),
//use a single marker with updated position
marker = new google.maps.Marker();
//set the latLng of the MVCObject
pos.set('latLng',new google.maps.LatLng(newMarker.latitude,
newMarker.longitude));
//bind the markers position to the latLng of the MVCObject
marker.bindTo('position',pos,'latLng');
marker.setMap(map);
setInterval(function(){
//the currently loaded script
var script=document.querySelector('script[src^="inputData.js"]'),
//the updated script
update=document.createElement('script');
//load-handler for the updated script
google.maps.event.addDomListenerOnce(update,'load',function(){
pos.set('latLng',new google.maps.LatLng(newMarker.latitude,
newMarker.longitude));
map.setCenter(pos.get('latLng'));
map.setZoom(18);
});
//replace current script with updated script
script.parentNode.replaceChild(update,script);
//load update
update.src='inputData.js?'+new Date().getTime();
},2000);
}
You don't need to create new instance of marker every time. Update your code with this and try:
var map;
var sendai = new google.maps.LatLng(38.259535, 140.846816);
var lastPosition;
var image = 'images/circle-16.png';
function initialize() {
var mapOptions = {
zoom: 12,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
var marker;
marker = new google.maps.Marker({
map: map,
icon: image,
draggable: false
});
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
setInterval(refreshData, 2000);
function refreshData() {
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
}
google.maps.event.addDomListener(window, 'load', initialize);
I have a Google Maps map with a markercluster, and various points. Generating the points like below with the event listener, it goes off for every single point on page load.
function mappyfuntime() {
var mapOptions = {
center: new google.maps.LatLng(51.481581,-3.17909),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("bigmap"), mapOptions);
<?php echo prepare_javascript(); ?>
var markers = [];
var marker = [];
linkto = new Array();
for(g=0; g<LocationsArray.length; g++) {
var latlng = new google.maps.LatLng(LocationsArray[g][0], LocationsArray[g][1]);
marker[g] = new google.maps.Marker({'position': latlng});
markers.push(marker[g]);
google.maps.event.addListener(marker[g], 'click', click_handler(PermalinksArray[g]));
}
var markerCluster = new MarkerClusterer(map, markers);
}
mappyfuntime();
function click_handler(link) {
alert(link);
}
However, if I change the google.maps.event.addListener to the following, the alert comes back undefined.
google.maps.event.addListener(marker[g], 'click', function() {
alert(PermalinksArray[g]);
});
And if I pass PermalinksArray[g] to the function, the same thing happens. Is there any way to get a piece of information from an array (which is globally defined) when its corresponding point is clicked on the map?
I guess the Permalinks Array comes from the php insert? Well then its not in global scope. Try puttung that php-insert at the top of your javascript script.
// set globals
var map;
var markers = [];
var PermalinksArray = ['...'];
var LocationsArray = ['...'];
function mappyfuntime() {
// init map
var mapOptions = {
center: new google.maps.LatLng(51.481581,-3.17909),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("bigmap"), mapOptions);
// create markers
for(g=0; g<LocationsArray.length; g++) {
// create new Position
var latlng = new google.maps.LatLng(LocationsArray[g][0], LocationsArray[g][1]);
// create new marker with position
var marker = new google.maps.Marker({'position': latlng});
// add event to marker
google.maps.event.addListener(marker, 'click', function() {
click_handler(marker, PermalinksArray[g]);
});
// push marker into markers array
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
}
function click_handler(marker, link) {
alert(link);
}
mappyfuntime();
I have created a Google Map with 2 markers and when a marker is clicked then the area's name appears in the info window. The information in the markers is loaded through a global defined array named cityList. You can find my code below.
<!doctype html>
<html lang="en">
<head>
<title>jQuery mobile with Google maps - Google maps jQuery plugin</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"> </script>
<script type="text/javascript">
var cityList = [
['Chicago', 41.850033, -87.6500523, 1],
['Illinois', 40.797177,-89.406738, 2]
],
demoCenter = new google.maps.LatLng(41,-87),
map;
function initialize()
{
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 7,
center: demoCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function addMarkers()
{
var marker, i;
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < cityList.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(cityList[i][1], cityList[i][2]),
map: map,
title: cityList[i][0]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(cityList[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
$(document).on("pageinit", "#basic-map", function() {
initialize();
});
$(document).on('click', '.add-markers', function(e) {
e.preventDefault();
addMarkers();
});
</script>
</head>
<body>
<div id="basic-map" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a> examples</h1>
<a data-rel="back">Back</a>
</div>
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:350px;"></div>
</div>
Add Some More Markers
</div>
</div>
</body>
</html>
I hope this helps.
I am trying to make a map with around 200 markers and for each marker an infowindow.
I tested it with two markers.
This is the site: http://www.bau-berater-kdr.de/pages/bauberater-karte.php
Code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 650px; height: 550px;"></div>
<script type="text/javascript">
var locations = [
['Koehn, Andrej<br>Dipl. Ing. Architektur<br>', 52.5299, 13.4149, 2],
['List, Walter, Dipl. Ing. (FH)<br>Büro für Baubiologie u. Grundstücksbewertung<br>www.Baubiologie-Mitteldeutschland.de', 51.4233, 12.2992, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: new google.maps.LatLng(52.5299, 13.4149),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
There is one main problem and I didn't found a solution:
When you click on a marker you will see 2 vertical scrollbars.. only need one and I thought the window would auto-size. Would like to increase the height. Does anyone know a solution?
And if anybody knows how to make this easier for such an amount of markers, I would be deeply grateful!
Handling Large Amounts of Markers in Google Maps
I've had success using the MarkerClusterer option on a map with several thousand markers.