JSON feed on Google map is showing nothing - javascript

I want the Google map show marker with JSON feeds. but it's not working. I can't find the actual problem. so here is my code:
var map;
// The JSON data
var json = [{
"OpperationErrorMsg":"",
"IsSuccess":true,
"ResultId":1000,
"Timestamp":"2016-10-12T18:00:07.0232702Z",
"Echo":null,
"InSandbox":true,
"DebugMessages":[
],
"MissingDetails":[
],
"ResponseData":[
{
"CallTimeLocal":"2016-10-10T06:28:48.7330000",
"IncidentId":3374,
"IncidentNumber":"HC2016004034",
"CallTime":"2016-10-10T10:28:48.7330000",
"ElapsedSeconds":0,
"Location":"2712 E HANNA AVE",
"BuildingName":null,
"BuildingNumber":null,
"NatureId":6743,
"FirePriorityId":1,
"CoordinateX":-82.429500000000,
"CoordinateY":28.003389000000
},
{
"CallTimeLocal":"2016-10-10T11:28:36.7000000",
"IncidentId":3382,
"IncidentNumber":"HC2016004042",
"CallTime":"2016-10-10T15:28:36.7000000",
"ElapsedSeconds":0,
"Location":"1220 APOLLO BEACH BLVD S",
"BuildingName":"Apollo Beach Marina",
"BuildingNumber":null,
"NatureId":8035,
"FirePriorityId":1,
"CoordinateX":-82.422369000000,
"CoordinateY":27.781254000000
},
{
"CallTimeLocal":"2016-10-10T14:29:59.8830000",
"IncidentId":3387,
"IncidentNumber":"HC2016004047",
"CallTime":"2016-10-10T18:29:59.8830000",
"ElapsedSeconds":0,
"Location":"9600 SHELDONWOOD RD",
"BuildingName":null,
"BuildingNumber":null,
"NatureId":6420,
"FirePriorityId":12,
"CoordinateX":-82.580530000000,
"CoordinateY":28.034779000000
},
{
"CallTimeLocal":"2016-10-10T15:27:37.7270000",
"IncidentId":3389,
"IncidentNumber":"HC2016004049",
"CallTime":"2016-10-10T19:27:37.7270000",
"ElapsedSeconds":0,
"Location":"4691 GALLAGHER RD",
"BuildingName":"Strawberry Crest High School",
"BuildingNumber":null,
"NatureId":7873,
"FirePriorityId":2,
"CoordinateX":-82.236450000000,
"CoordinateY":28.021233000000
}
],
"CurrentStatusData":null
}];
function initialize() {
// Giving the map som options
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(25.0,-80.0)
};
// Creating the map
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Looping through all the entries from the JSON data
for(var i = 0; i < json.length; i++) {
// Current object
var obj = json[i];
// Adding a new marker for the object
var marker = new google.maps.Marker({
position: new google.maps.LatLng(obj.CoordinateY,obj.CoordinateX),
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
title: obj.BuildingName // this works, giving the marker a title with the correct title
});
// Adding a new info window for the object
var clicker = addClicker(marker, obj.title);
} // end loop
// Adding a new click event listener for the object
function addClicker(marker, content) {
google.maps.event.addListener(marker, 'click', function() {
if (infowindow) {infowindow.close();}
infowindow = new google.maps.InfoWindow({content: content});
infowindow.open(map, marker);
});
}
}
// Initialize the map
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script src="https:////cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="map-canvas"></div>
I will be using it on a HTML page. Though the JSON data will be updated automatically so i can't change the JSON Arrays.
Thanks!

I found these problems in your code:
In your loop where you create each marker, you are looping over the json array. However, this is not your array of marker data. json[0] is your main object, and json[0].ResponseData is the marker array that you need to loop over. So I put that value in a variable named responses and looped over that instead. I don't know if the JSON data could have more than one object in its outermost array; if it does you would need an outer loop to handle those. For now I assumed there is just one outer object addressed with json[0].
When you call addClicker you pass in obj.title which doesn't exist. Presumably you meant obj.BuildingName.
Your click handler references a variable called infowindow, but on the first click that variable does not exist and causes an error. So I declared infowindow as a global window.
So, how did I find these problems? Using the JavaScript debugger. Normally I would add a debugger; statement at the beginning of the initialize() function and single step through the code to see what is going on. This would reveal that where the main loop sets var obj = json[i]; it isn't getting the expected value.
That works great on a normal web page, but it doesn't seem to work well in the embedded snippet here on SO. (The debugger shows the wrong source line.) So instead I started adding console.log(); statements where it looked like things might be going wrong, such as console.log( 'obj:', obj ); immediately after the var obj = assignment.
Also, it's nice to automatically zoom and center the map according to where the markers are located. I added a bit of code using a LatLngBounds which is extended for each marker, and then a map.fitBounds() after all the markers are created. If you do that you don't need to explicitly zoom and center the map when first creating it, so I removed those. (Otherwise the map is displayed at one position and then repositioned.)
One caveat with the fitBounds(): if there were no markers, then the map wouldn't get displayed at all. To handle that case you would want to check for the case where responses.length is zero and call map.setZoom() and map.setCenter() with default values.
I marked the changed lines with //// to make them easy to find:
var map, infowindow; ////
// The JSON data
var json = [{
"OpperationErrorMsg":"",
"IsSuccess":true,
"ResultId":1000,
"Timestamp":"2016-10-12T18:00:07.0232702Z",
"Echo":null,
"InSandbox":true,
"DebugMessages":[
],
"MissingDetails":[
],
"ResponseData":[
{
"CallTimeLocal":"2016-10-10T06:28:48.7330000",
"IncidentId":3374,
"IncidentNumber":"HC2016004034",
"CallTime":"2016-10-10T10:28:48.7330000",
"ElapsedSeconds":0,
"Location":"2712 E HANNA AVE",
"BuildingName":null,
"BuildingNumber":null,
"NatureId":6743,
"FirePriorityId":1,
"CoordinateX":-82.429500000000,
"CoordinateY":28.003389000000
},
{
"CallTimeLocal":"2016-10-10T11:28:36.7000000",
"IncidentId":3382,
"IncidentNumber":"HC2016004042",
"CallTime":"2016-10-10T15:28:36.7000000",
"ElapsedSeconds":0,
"Location":"1220 APOLLO BEACH BLVD S",
"BuildingName":"Apollo Beach Marina",
"BuildingNumber":null,
"NatureId":8035,
"FirePriorityId":1,
"CoordinateX":-82.422369000000,
"CoordinateY":27.781254000000
},
{
"CallTimeLocal":"2016-10-10T14:29:59.8830000",
"IncidentId":3387,
"IncidentNumber":"HC2016004047",
"CallTime":"2016-10-10T18:29:59.8830000",
"ElapsedSeconds":0,
"Location":"9600 SHELDONWOOD RD",
"BuildingName":null,
"BuildingNumber":null,
"NatureId":6420,
"FirePriorityId":12,
"CoordinateX":-82.580530000000,
"CoordinateY":28.034779000000
},
{
"CallTimeLocal":"2016-10-10T15:27:37.7270000",
"IncidentId":3389,
"IncidentNumber":"HC2016004049",
"CallTime":"2016-10-10T19:27:37.7270000",
"ElapsedSeconds":0,
"Location":"4691 GALLAGHER RD",
"BuildingName":"Strawberry Crest High School",
"BuildingNumber":null,
"NatureId":7873,
"FirePriorityId":2,
"CoordinateX":-82.236450000000,
"CoordinateY":28.021233000000
}
],
"CurrentStatusData":null
}];
function initialize() {
// Giving the map som options
var mapOptions = {
////
};
// Creating the map
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var bounds = new google.maps.LatLngBounds(); ////
// Looping through all the entries from the JSON data
var responses = json[0].ResponseData; ////
for(var i = 0; i < responses.length; i++) { ////
// Current object
var obj = responses[i]; ////
// Adding a new marker for the object
var position =
new google.maps.LatLng( obj.CoordinateY, obj.CoordinateX ); ////
bounds.extend( position ); ////
var marker = new google.maps.Marker({
position: position, ////
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
title: obj.BuildingName
});
// Adding a new info window for the object
var clicker = addClicker(marker, obj.BuildingName); ////
} // end loop
map.fitBounds( bounds ); ////
// Adding a new click event listener for the object
function addClicker(marker, content) {
google.maps.event.addListener(marker, 'click', function() {
if (infowindow) {infowindow.close();}
infowindow = new google.maps.InfoWindow({content: content});
infowindow.open(map, marker);
});
}
}
// Initialize the map
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script src="https:////cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="map-canvas"></div>

Related

dynamically adding markers to google map on click

I am trying to create a website that has a google map in one column and in the second is a list of items with location elements. On clicking one of these items, I would like to drop a pin in the google map. I am having trouble updating the markers on the google map. I can add one marker at initialization of the map, but cannot get new markers to be dropped. Here is my code: https://gist.github.com/aarongirard/32f80f17e19d3e0389da. The issue occurs in the if else clause within the click function.
Any help is appreciated!!
//global variables //google map
var map;
var marker;
var currentMakerli;
function initialize() {
//set latlng of starting window of map
var mapOptions = {
center: { lat: 34.073609, lng: -118.562313},
zoom: 14,
};
//set map using above options and attach to given element
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//construct new marker; constructor takes an object with position and title properties
//get lat long for first marker
var latlng = new google.maps.LatLng(34.073514, -118.562348);
marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Home"
});
//on click of li add new marker or remove if marker already exists
$(".DataList li").click(function(){
//if current marker set to this already
//remove marker
if ( $(this).attr('id') === 'current') {
marker.setMap(null);
$(this).attr('id', '');
} else {
$(this).attr('id','current');
var latlngarr = getLatLngFromString($(this).attr('data-position'));
var lat = latlngarr[0];
var lng = latlngarr[1];
thisLatlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
});
//marker.setMap(map);
}
});
}
//set map
google.maps.event.addDomListener(window, 'load', initialize);
function getLatLngFromString(string){
var array = string.split(',');
array[0] = parseFloat(array[0]);
array[1] = parseFloat(array[1]);
return array;
}
You must store the marker in a way in which you are able to get a relation between the <li> and the marker, e.g. via $.data
simple example:
function initialize() {
//set latlng of starting window of map
var map = new google.maps.Map($('#map-canvas')[0], {
center: { lat: 34.073609, lng: -118.562313},
zoom: 14,
disableDefaultUI:true
}),
home = new google.maps.Marker({
position: { lat: 34.073514, lng: -118.562348},
map: map,
title: "Home",
icon:'http://maps.google.com/mapfiles/arrow.png'
});
map.controls[google.maps.ControlPosition.TOP_LEFT].push($(".DataList")[0]);
//on click of li add new marker or remove if marker already exists
$(".DataList li").click(function(){
var that=$(this);
//when there is no marker associated with the li we create a new
if(!that.data('marker')){
that.data('marker',new google.maps.Marker({position:(function(ll){
return new google.maps.LatLng(ll[0],ll[1]);
}(that.data('position').split(/,/)))}));
}
var marker=that.data('marker');
//simply check the markers map-property to decide
//if the marker has to be added or removed
if(marker.getMap()){
that.removeClass('current');
marker.setMap(null);
}
else{
that.addClass('current');
marker.setMap(map);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,body,#map-canvas{height:100%;margin:0;padding:0}
.current{background:#f1f1f1;}
.DataList{background:#fff;padding:0;}
.DataList li{cursor:pointer;padding:4px;list-style-position:inside;}
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<ul class="DataList">
<li data-position="34.0717825, -118.567396">Santa Ynez Canyon Park</li>
<li data-position="34.0787989, -118.572502">Palisades Country Estates</li>
<li data-position="34.078375, -118.56098">Highland Recreation Center</li>
</ul>
<div id="map-canvas"></div>
Related to the comments:
You didn't mess up with variable-names, my examples uses less variables, but you may use more variables when you want to.
I prefer to avoid variables when I need to access an object only once.
The marker will be created here(and stored as a property of the <li/>):
//when there is no marker associated with the li we create a new
if(!that.data('marker')){
that.data('marker',new google.maps.Marker({position:(function(ll){
return new google.maps.LatLng(ll[0],ll[1]);
}(that.data('position').split(/,/)))}));
}
The part that splits the data-position-attribute is this:
(function(ll){
return new google.maps.LatLng(ll[0],ll[1]);
}(that.data('position').split(/,/)))
It's a so-called "self-executing anonymous function", which returns the desired value(a LatLng) which will be used as position of the Marker. The splitted data-position-attribute will be used as argument for this function
that.data('position').split(/,/)
getMap() returns whatever the map-property has been set to, either a google.maps.Map-instance or null (when you want to remove the marker or when the property is not set). Although it's not a boolean value it evaluates to either true(when it's a map) or false(when it's null), so it may be used as condition.
The that-variable is always a new variable, that's correct, but it will always be a reference to the same object, the clicked <li/>. The marker has been stored as property of this object.

Google Maps API v3 binding events to multiple maps

I've got a page with two Google maps on, using the v3 API. Currently they have one pin each, with the same lat & long set for each pin, although one of the maps will have other pins added at a later date (when I can get this to work!) The maps are generated by looping through an object, so further maps can be added simply if needed.
What I am trying to do is bind the bounds_changed event once to both maps, to run map.setZoom() after map.fitBounds() has been run. The event, however, only binds to the last map to be set up, so does not reset the zoom on the first map.
Link to JSFiddle replicating the issue: http://jsfiddle.net/pkhb8mvz/7/
(For a more clear example of what the event is being bound to, change the event to listen on click rather than bounds_changed then try clicking on the first map and watch the zoom level change on the second map)
Any help greatly appreciated!
The problem is that the map variable is being redefined on each iteration of your loop, so by the time your event listener callback runs it will operate on the second google.maps.Map object. The simplest solution is to capture the value of the map variable on each iteration using a closure, like so:
(function (map) {
var listener = new google.maps.event.addListenerOnce(map, "bounds_changed", function () {
if (!opts.center) {
map.setZoom(opts.zoom);
};
});
}) (map);
I forked your JSFiddle to demonstrate the idea: https://jsfiddle.net/e8qbr8qL/
Created this fiddle that works based on this answer https://stackoverflow.com/a/5839041/2321666.
Apart from the function you need to add, your map variable should be an array so that there is one instance of each map.
map[i] = new google.maps.Map($(maps[i].mapElement)[0], opts);
If you need any explanation of the code please ask, but i think there is enough info about javascript closures in the post added.
You can't add a listener to multiple maps unless you keep references to all of them, currently you are only keeping a reference to the last map created.
// use function closure to associate the map with its bounds listener
addBoundsListener(map, opts, bounds);
map.fitBounds(bounds);
}
function addBoundsListener(map, opts, bounds) {
// If no center option has been specified, center the map to
// contain all pins and reset the zoom
var listener = new google.maps.event.addListenerOnce(map, "bounds_changed", function () {
if (!opts.center) {
map.setZoom(opts.zoom);
}
});
}
updated fiddle
code snippet:
var maps = {
"propertyLocation": {
"mapElement": "#map1",
"options": {
"zoom": 10,
"streetViewControl": false
},
"pins": [{
"title": "Test 1",
"lat": "52.1975331616",
"long": "0.9771180153"
}]
},
"localArea": {
"mapElement": "#map2",
"options": {
"zoom": 14,
"streetViewControl": false
},
"pins": [{
"title": "Test 2",
"lat": "52.1975331616",
"long": "0.9771180153"
}]
}
};
// Sensible defaults
var defaults = {
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggable: true
};
for (var i in maps) {
// Extend the options
var opts = $.extend(true, defaults, maps[i].options),
marker,
map,
bounds = new google.maps.LatLngBounds();
// Create the map
map = new google.maps.Map($(maps[i].mapElement)[0], opts);
// Create all pins
for (var p = 0; p < maps[i].pins.length; p++) {
var pin = maps[i].pins[p];
marker = new google.maps.Marker({
position: new google.maps.LatLng(pin.lat, pin.long),
map: map,
title: pin.title,
icon: pin.icon
});
// Extend the bounds of the map to contain the marker
bounds.extend(marker.position);
}
// use function closure to associate the map with its bounds listener
addBoundsListener(map, opts, bounds);
map.fitBounds(bounds);
}
function addBoundsListener(map, opts, bounds) {
// If no center option has been specified, center the map to
// contain all pins and reset the zoom
var listener = new google.maps.event.addListenerOnce(map, "bounds_changed", function() {
if (!opts.center) {
map.setZoom(opts.zoom);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div style="width: 500px; height: 500px;" id="map1"></div>
<div style="width: 500px; height: 500px;" id="map2"></div>

Change icon on mouseover/out fails

I'm tearing my hair out over this code. As you may guess, I'm relatively new to coding. I would appreciate any insight you have into why it is not working.
I am trying to change marker icons on mouseover/out. I am trying to create and add listeners in a for-loop. In the loop, the markers are created from an array of locations and pushed to another array, a listener is added for mouseover events to change the icon, and another listener is added for mouseout events to nullify the marker icon. The code below displays the map, adds the markers and seems to listen for mouseover and mouseout events (the cursor changes when hovering over a marker), but the icon does not change at these events.
function initialize(){
//Marker locations
var NYC = new google.maps.LatLng(40.721505, -74.004783);
var LA = new google.maps.LatLng(34.049519, -118.238698);
var Chicago = new google.maps.LatLng(41.877461, -87.624352);
var Seattle = new google.maps.LatLng(47.606747, -122.330349);
var Miami = new google.maps.LatLng(25.788661, -80.226617);
var Boston = new google.maps.LatLng(42.357913, -71.059217);
var Houston = new google.maps.LatLng(29.758182, -95.364213);
var KansasCity = new google.maps.LatLng(39.097781,-94.588079);
var locations = new Array(NYC, LA, Chicago, Seattle, Miami, Boston, Houston, KansasCity);
//Array to store markers
var markers = new Array ();
//Icon
var gif = 'http://demers-ambulances.com/assets/img/news/mapPinOver2.gif';
//Map options
var mapOptions = {
center: KansasCity,
zoom: 5,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.TOP_LEFT
},
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
position: google.maps.ControlPosition.TOP_RIGHT,
},
};
//Create map
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//Create markers and add listener to change marker icon on mouseover/out
for (i = 0; i<locations.length; i++){
var marker = new google.maps.Marker({
position: locations[i],
draggable: true,
map: map,
});
markers.push(marker);
google.maps.event.addListener(markers[i], 'mouseover', function() {
markers[i].setIcon(gif);
});
google.maps.event.addListener(markers[i], 'mouseout', function() {
markers[i].setIcon(null);
});
};
};
google.maps.event.addDomListener(window, 'load', initialize);
Thanks for your help :)
Closure problem: there is error reported:
Uncaught TypeError: Cannot read property 'setIcon' of undefined
Code has to be changed to:
(function(i) {
google.maps.event.addListener(markers[i], 'mouseover', function() {
markers[i].setIcon(gif);
});
google.maps.event.addListener(markers[i], 'mouseout', function() {
markers[i].setIcon(null);
});
})(i);
Basically the problem is in here:
for (i = 0; i<locations.length; i++){
var marker = new google.maps.Marker({
position: locations[i],
draggable: true,
map: map,
});
markers.push(marker);
google.maps.event.addListener(markers[i], 'mouseover', function() {
markers[i].setIcon(gif);
});
google.maps.event.addListener(markers[i], 'mouseout', function() {
markers[i].setIcon(null);
});
};
This code looks innocent, but the problem comes from the part that, once the loop has finished executing and our event listeners are called, the variable i is already equal to locations.length.
So whenever the event listener is called, i is already changed to locations.length, and markers[i] will return undefined, because the last push index was i = locations.length - 1
since the loop condition is i<locations.length.
Since markers[i] is undefined when the event listener is called, then it will throw the following error as it doesn't have setIcon method anymore: TypeError: Cannot read property 'setIcon' of undefined.
To fix this, you should capture value of i, in a closure(as Anto Jurković described above, don't forget to upvote him):
(function(i) {
google.maps.event.addListener(markers[i], 'mouseover', function() {
markers[i].setIcon(gif);
});
google.maps.event.addListener(markers[i], 'mouseout', function() {
markers[i].setIcon(null);
});
})(i);
Here we create a function on each loop and call it with i immediately so the value of i is captured in the closure, and since javascript functions have block scope(loops don't), the variable i will be the same for each iteration of loop.
The problem and it's solution is also described in the following question: Javascript closure inside loops - simple practical example
After further experimenting with the code that Anto and Farid recommended I found another solution. For this solution a function is created outside the initialize function to add listeners to the markers, and then called when each marker is created in the for loop. If you have any thoughts on this, please comment below. I have no clue if this is a good way to do this, I just know it works :)
for (i = 0; i<locations.length; i++){
var marker = new google.maps.Marker({
position: locations[i],
draggable: true,
map: map,
});
animateit(marker);
markers.push(marker);
};
};
function animateit(marker) {
google.maps.event.addListener(marker, 'mouseover', function() {
marker.setIcon(gif);
});
google.maps.event.addListener(marker, 'mouseout', function() {
marker.setIcon(null);
});

Getting data stored in additional field of googlemap's marker

I'm working with google maps api and javascript which I am not much familiar with. Here's the code I use to draw markers on my map. I get Latitudes and Longitudes from my database:
var geocoder;
var map;
var jsonStr = '<?php echo json_encode($arajka) ?>';
var LatLong = JSON.parse(jsonStr);
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: new google.maps.LatLng(50.000001, 20.000001),
zoom: 12
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var marker = [];
for(var i=0;i<LatLong.length;i++){
var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
marker.push(new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login}));
}
// trying to set some listener but it fails.
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(8);
map.setCenter(marker.getPosition());
alert("ASDASDASD" + marker.ajdi);
});
}
So, this listener doesn't work, I don't know why. Well, I expect that it doesn't exactly know what marker is it about. When I tried to do it with a single one, like in tutorial, it worked properly. I don't know what to do when I have this array. Any suggestions please?
You have several mistakes in your code:
As #Hollister mentions, marker is an array, so you need to put the addListener call inside the loop;
You have to store the additional marker data into the marker, not into the marker array;
you have to use this in the listener, not marker.
for(var i=0;i<LatLong.length;i++){
var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
var this_marker = new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login});
this_marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
marker.push(this_marker);
// trying to set some listener but it fails.
google.maps.event.addListener(this_marker, 'click', function() {
map.setZoom(8);
map.setCenter(this.getPosition());
alert("ASDASDASD" + this.ajdi);
});
}

Automatically opening marker info pane on google map

I've created a custom map with most things I want on it (custom icon and custom info bubble), however I can't find a solution to automatically open the markers info window on load, I've done alot of searching but can't seem to find anything the code I have so far is as follows, any help would be much appreciated:
function initialize() {
var myLatlng = new google.maps.LatLng(54.325109,-2.742226);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var countries = [
{
title:'Remedy',
lat:54.3210,
lon:-2.7438,
content:"<h2>Remedy</h2><p>address, <br />location, <br />postcode</p> <p><b>T:</b> 07595 153 835 <br /><b>E:</b> <a href='mailto:email'>email</a></p>"
}
];
for (var i = 0; i < countries.length; i++) {
var c = countries[i];
c.marker = new google.maps.Marker({
position: new google.maps.LatLng(c.lat, c.lon),
map: map,
icon: '/wp-content/themes/remedy/display_images/google_map_icon.png',
title: c.title});
c.infowindow = new google.maps.InfoWindow({content: c.content});
google.maps.event.addListener(c.marker, 'click', makeCallback(c));
}
function makeCallback(country) {
return function () {
country.infowindow.open(map, country.marker);
};
}
infowindow.open(map, marker);
}
Maybe it's not working because you just created the instance of the Map and didn't wait for the complete load of the map to open the InfoWindow.
Try something like this:
google.maps.event.addListenerOnce(map, 'tilesloaded', function(event) {
infowindow.open(map, marker);
});
According to the reference:
http://code.google.com/intl/en/apis/maps/documentation/javascript/reference.html#Map
tilesloaded - This event is fired when the visible tiles have finished loading.
Hmm, inforwindow does not refer to anything in your code, which is why it is not working.
Since you have one country in the list as of now you can do a quick test and intialize the infowindow variable with an actual info window, or better yet also since you have 1 item in the list, just define c to be outside the loop so you can access it and then open the popup passing it the map and the marker, something like this (assuming c has been defined outside the loop)
c.infowindow.open(map, c.marker);
var infowindow = new google.maps.InfoWindow({
content: "Test Route",
position: new google.maps.LatLng(38.8709866, -77.208055),
});
infowindow.open(map);

Categories