GoogleMaps InfoWindow appear at a corner - javascript

here is my code in html to generate marker and infowindow(with ruby on rails)
var marker=[]
function initMap() {
var latLng1 = new google.maps.LatLng(1.352083, 103.819836);
var myOptions = {
zoom: 12,
center: latLng1,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
for(i=0;i<gon.astatic.length;i++){
var latLng = new google.maps.LatLng(gon.astatic[i][1], gon.astatic[i][2]);
if(i<2){
marker[i] = new MarkerWithLabel({position: latLng, map: map,icon:"/assets/green_MarkerV.png" ,labelClass: "labels",labelContent: gon.astatic[i][3]});}
else
{
marker[i] = new MarkerWithLabel({position: latLng, map: map,icon:"/assets/green_MarkerN.png" ,labelClass: "labels",labelContent: gon.astatic[i][3]});
}
var iw =new google.maps.InfoWindow({content: 'HI' });
google.maps.event.addListener(marker[i],"mouseover",function(e){iw.open(map,marker[i]);})
}
this gon is just some 'stupid' method I use to pass data from ruby on rails controller to javascript.
for all marker,the infowindow all appear at corner.
But for my another map(which have only one marker with infowindow)it works fine.
What might be my problem?why this infowindow appear in wrong position?Instead of just above the marker?
EDIT:
After half day's trouble shoot,I feel the problem is at
google.maps.event.addListener(marker[i],"mouseover",function(e){iw.open(map,marker[i]);})
when the listener calls back,the value inside marker is i ,which is not a actual number,so the marker display at a corner.I feel the problem is can't pass variable into addListener,can only put in actual number.How to solve this?

Each instance of the function declared inside the for loop shares the same closure containing the value i, and so all of your addListener calls are essentially calling iw.open(map, undefined) since i will be off the end of the array at the end of the iteration.
See JavaScript closure inside loops – simple practical example for sample solutions to this problem, and How do JavaScript closures work for more information about closures in JavaScript in general.

The problem is with your MarkerWithLabel library. Infowindow take position from marker. Try use this link http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.8/docs/examples.html . It has all the things that you want to implement. It it's not work then you can also set position for infowindow with setPosition() function just pass latlng that you used to create marker and you are done.

i dont recommend using new gem just to pass data from ruby to js...you can do this simply by many ways...your code seems good but i cannot say how gon is handling your js script.Please take a look at this similar question where i have implemented the same dynamic map with dynamic markers and infowindows.This code is working great
see here

Related

Getting marker from map.data class use geojson google maps

first of all I was initiate marker from geojson, and how I can get the marker if i want use marker for listener/action?
this is my script
var map;
function initMap() {
//makes map
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -6.9034482, lng: 107.6081381},
zoom: 9,
styles: [{"featureType":"water","stylers":[{"saturation":43},{"lightness":-11},{"hue":"#0088ff"}]},{"featureType":"road","elementType":"geometry.fill","stylers":[{"hue":"#ff0000"},{"saturation":-100},{"lightness":99}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"color":"#808080"},{"lightness":54}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#ece2d9"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"color":"#ccdca1"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#767676"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]},{"featureType":"poi","stylers":[{"visibility":"off"}]},{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#b8cb93"}]},{"featureType":"poi.park","stylers":[{"visibility":"on"}]},{"featureType":"poi.sports_complex","stylers":[{"visibility":"on"}]},{"featureType":"poi.medical","stylers":[{"visibility":"on"}]},{"featureType":"poi.business","stylers":[{"visibility":"simplified"}]}]
});
//load marker from geojson
map.data.loadGeoJson('<?php echo base_url().'index.php/json_site/geojsongetmap'?>');
// set style marker
map.data.setStyle(function(feature){
var tit = feature.getProperty('nm_site');
return{
title: tit,
icon: '<?php echo base_url()?>assets/images/mark3.png'
};
});
//marker event
map.data.addListener(marker, 'click', function(event) {
map.setZoom(11);
map.setCenter(marker.getPosition()); // I need to get the position of the marker who i clicked
});
}
how I can make action listener if I initiate marker from geojson?
and how I can get the marker who existing in my map?
please help me, any suggest would be appreciated
thanks
Instances of the google.maps.Data.Point class are not exactly a drop-in replacement for traditional google.maps.Marker objects. For starters, they are abstract data, not tied to a particular representation. It's up to the parent google.maps.Data layer to decide how to draw them.
However, you can still capture events, with the caveat that the click happens on the Data layer, which receives a mouseEvent as argument. This argument contains the feature over which you just clicked.
This means you need to declare:
google.maps.event.addListener(map.data,'click',function(mouseEvent) {
var clickedFeature = mouseEvent.feature,
featureGeometry = clickedFeature.getGeometry(),
featurePosition = featureGeometry.get();
map.setCenter(featurePosition);
});
Please take into consideration that ingesting geoJson with the Data layer can result not just in Point geometries. If you get a mix of points, polygons and linestrings, anything different from a point won't return a latLng object when you call its get method.

Google map v3 API change today?

My map redraws seem to be failing because (at the least) I have been dynamically setting the center via
var currCenter = gmap.getCenter();
Then:
var mapOptions = {
center: new google.maps.LatLng(currCenter.ob, currCenter.pb),
zoom: currZoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
Appears currCenter.ob is suddenly undefined this morning. It now looks like it's pb & qb instead of ob & pb. I'm in the process of trying to fix the code, is there anything else anyone knows of that was changed?
EDIT: They're undocumented API fields I shouldn't be using, nevermind I fixed it with the info below. Thanks.
I am assuming gmap is a google map object. If that is the case, then getCenter already returns a LatLng object, so creating a new object via
new google.maps.LatLng()
Is somewhat useless, you could simply use currCenter directly.
The problem is that Api Google maps constantly changing this values (ob, .pb) to Latitude and Longitude, you must use lat() and lng() functions to have a stable version
var mapOptions = {
center: new google.maps.LatLng(currCenter.lat(), currCenter.lng()),
zoom: currZoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
greetings!
To answer you question. YES. Google Maps API did changed last night. I was doing the same thing you did (calling .ob and .pb), but found that I had to change them to .pb and .qb in my code respectively in order to get the Lat and Long.
Rewrote them as .lng() and .lat() instead of .ob, .pb, .qp. I believe that these members should be more stable if you still want to use unofficial member names.

Javascript argument parameters and google maps

I'm introducing myself to Google Maps API, and to JavaScript as well.
I already have set my map on my website, and now I'm trying to dynamically set multiple markers on the same map.
For that, I wrote this function:
function teste(lat,long){
alert (lat);
alert (long);
//var companyPos3 = new google.maps.LatLng(41.545308,-8.421782);
var companyPos3 = new google.maps.LatLng(lat,long);
var companyMarker3 = new google.maps.Marker({
position: companyPos3,
map: map,
// icon: companyLogo,
title:"Mar!!!" });
//}
...
}
And my problem resides right here. I can't set the google.maps.LatLng with 'lat' and 'long' function parameters. However, the alert dialog messages pop up, showing the values that are from PHP.
I tried also to remove the alert function but the marker didn't show as well.
I'm not sure if it there is a Google Maps API trick, or JavaScript trick.
Oh, and if I set the values as the commented line, it works, but I don't want this solution :).
long is the reserved word in JS. Please check here. So, please try lng instead of long also for setting icon please see here. Try something like
function teste(lat,lng){
alert (lat);
alert (lng);
//var companyPos3 = new google.maps.LatLng(41.545308,-8.421782);
var companyPos3 = new google.maps.LatLng(lat,lng);
var companyMarker3 = new google.maps.Marker({
position: companyPos3,
map: map,
// icon: companyLogo,
title:"Mar!!!" });
//}
...
}

Google map error: a is null

I have a program that I want to use google maps for. The problem is I get an error that says a is null where a is a var used in the google map api. Here is how I call my google map:
//Creates a new center location for the google map
var latlng = new google.maps.LatLng(centerLatitude, centerLongitude);
//The options for the google map
var myOptions = {
zoom: 7,
maxZoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Creates the new map
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
And here is what my HTML tag looks like:
<div id = "map_canvas"></div>
I get the lat and lng on page load through the url. These values are passed in correctly so I know that is not the problem. I think that it has to do with the var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); not being correct. Any suggestions?
EDIT: Here is the error message:
a is null
fromLatLngToPoint(a=null)
yg(a=null, b=Object { zoom=7, maxZoom=12, more...})
d(d=Document Default.aspx?lat=30.346317&lng=105.46313, f=[function()])
d(a=undefined)
d()
[Break On This Error] function Qf(a){a=a.f[9];return a!=i?a:...);function sg(a){a[ic]&&a[ic]Vb}
Make sure you specify the size of the element that holds the map. For example:
<div id="map_canvas" style="width: 500px; height: 500px;"></div>
Also make sure your map variable is defined in the global scope and that
you initialize the map once the DOM is loaded.
You are probably not listening for the onload event that fires when the page is completely loaded. As a result, your script is running but the div you are creating doesn't yet exist. Use jQuery to listen for this event, like so:
$(document).ready(function () {
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
});
If you don't want to use jQuery, then add an event listener to body.onload
This rather cryptic error means that the script can't find the map div.
This could happen for a couple of reasons.
1. You're using the wrong ID to refer to the map.
Check your ids (or classes) and make sure the element you're referring to actually exists.
2. You're executing the script before the DOM is ready.
Here's a jQuery example. Notice we're triggering initialise on document ready, not onDOMReady. I've taken the liberty of wrapping the script in a closure.
(function($) {
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
}
$(document).ready(initialize);
})(jQuery)
You could also use:
google.maps.event.addDomListener(window, 'load', initialize);
if you prefer a Google solution.
Had the exact same problem and this is have i fixed it for me.
The thing was that I had 2 google maps in my website - one in the footer and the other one on the contact page, but i called them both in one JS file like so:
var map1 = new google.maps.Map(document.getElementById("map-canvas-footer"), settings1);
var map2 = new google.maps.Map(document.getElementById("map-canvas"), settings2);
But the thing is that the object with id="map-canvas" was located only on the contact page.
So at first you have to check if that element exists on the page like so:
if ($("#map-canvas-footer").length > 0){
var map1 = new google.maps.Map(document.getElementById("map-canvas-footer"), settings1);
}
if ($("#map-canvas").length > 0){
var map2 = new google.maps.Map(document.getElementById("map-canvas"), settings2);
}
I hope this can help someone else as well ;)
This happens when the map is not yet loaded. You should build your map when the Maps API JavaScript has loaded. Executing the function to initialize your map only when the API has fully loaded passing it to the "callback" parameter in the Maps API bootstrap.
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
This is actually in the Maps API Docs here. Hope this helps!
Make sure that your canvas div (Div associated with the map) exists.
Sometimes, if we rename the div's id attribute.
Then it creates problem as it does not get the canvas div.
I got this error once. Make sure the map script runs only on pages using the map. You can check if the map exists by using an "if". Something like this:
if ($('mapClass').length>0) { // here you run the google maps functions }
See ya
Solved, the google map type a error, make sure you get object var map = document.getElementById('map-canvas') returning properly using alert(map). Check the div container id name same as specified in getElementByid.
I have also stuck with the same type a error, fixed it by checking getElementByid('map-canvas'). Sample code enter link description here
I have fixed it removing my "style" property from the "div" tag an declaring it correctly, in a css file
My response is bit old but for those who still come here for reference, I have a similar solution. I put map initialization code as specified here https://developers.google.com/maps/documentation/javascript/adding-a-google-map
inside jQuery document ready function. Below is the code that worked in my case:
$(document).ready(function () {
var uluru = {lat: -25.344, lng: 131.036};
var map = new google.maps.Map( document.getElementById('embedmap'), {zoom: 14, center: uluru} );
var marker = new google.maps.Marker({position: uluru, map: map});
});

How can I make infowindows resize for tweets in Google Maps v3 with Javascript

I'm trying to add a few tweets to an infowindow in Google Maps. I get the tweets to display in a div that is the content of my infowindow, but it's the wrong size.
I thought by calling 'content_changed' when the marker is clicked, the infowindow would resize - it doesn't.
I'm sure this is pretty straightforward, can someone help me out?
Thanks,
James
var myLatlng = new google.maps.LatLng(51.500261,-0.126793);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
});
var infowindow = new google.maps.InfoWindow();
infowindow.setContent(document.getElementById("station"));
google.maps.event.addListener(marker, 'click', function() {
google.maps.event.trigger(infowindow, 'content_changed');
infowindow.open(map,marker);
});
Try to call infowindow.close(); before open(). I'm pretty sure that it will force it to rerender
This isn't exactly a supported solution, but after poking around in Firebug, I found an easy way to force a resize on the window:
infoWindow.b.contentSize = new google.maps.Size(w, h);
google.maps.event.trigger(infoWindow.b, 'contentsize_changed');
As far as what the real W/H should be set to on the first line, that's a matter of looking at infoWindow.b.contentNode and getting a real width/height either through the standard properties or jQuery's methods.
I'm not sure exactly what infoWindow.b is, but it seems like it's some sort of "content" object. I wish they would expose this and document it.
I ended up with:
infoWindowLinea.setContent(infoWindowLinea.getContent());

Categories