Google Maps - all buttons are disabled on load - wordpress

I'm writing a Wordpress page for a client that displays some text and a Google Map based on data loaded from a database.
So far I've gotten most of it to work. The Google Maps however begins to load then mysteriously "blues" out displaying only what looks like ocean with all the other options (zoom in/out, street view, etc.) greyed out.
There are no JavaScript errors available from FireBug etc.
The divs containing the map (#container, and #map-canvas ) are set to real pixel values.
The solution given here yields no positive results.
This is what the end result looks like:
Any ideas would be extremely welcome.
Edit:
Code snip per request:
echo '<script>function initialize(e,t,n){e=parseFloat(e);t=parseFloat(t);var r=new google.maps.LatLng(e,t);var i;var s;var o={center:r,zoom:14,mapTypeId:google.maps.MapTypeId.ROADMAP};s=new google.maps.Map(document.getElementById("map-canvas"),o);i=new google.maps.Marker({map:s,draggable:false,animation:google.maps.Animation.DROP,position:r,title:n});google.maps.event.addDomListener(window,"load",initialize)}jQuery(function($){initialize("'.$detail['latitude'].'","'.$detail['longitude'].'","'.$detail['name'].'")})</script>';
echo '
<div id="container" style="height:500px;width:500px;">
<div id="information">
<h2>'.$detail['name'].'</h2>
<p>'.$detail['description'].'</p>
<p>'.$detail['address'].'</p>
</div>
<div id="map-canvas" style="width:300px;height:200px;">
</div>
</div>
';
Un-minified version of the JS:
function initialize(lat,lng,name) {
lat = parseFloat(lat);
lng = parseFloat(lng);
var ourLocation = new google.maps.LatLng(lat,lng);
var marker;
var map;
var mapOptions = {
center: ourLocation,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
marker = new google.maps.Marker({
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
position: ourLocation,
title:name
});
google.maps.event.addDomListener(window,"load",initialize);
};
jQuery(function($){
initialize(lat,lng,name);
// the variables lat, lng, and name are replaced with php variables in the code
});

I figured it out. Took a little while, but...
Wordpress hates the jQuery call for some reason or another.
I noticed that in the JS console, if I called the initialize function with the variables I'd rip from the generated source then the map would magically work.
Instead of using jQuery, I just used the windows onload event.
window.onload = function() { initialize('.$detail['latitude'].','.$detail['longitude'].',"'.$detail['name'].'"); }
Which magically works.
Lesson learned, jQuery and Wordpress are like Strawberry Chocolate Milk and India Pale Ales: they don't mix well.
Thank you everyone that contributed.

Related

google maps infoWindow click event re-renders map-canvas in Meteor

Hey Im trying to use google maps within my MeteorJS project to have google maps display on a map all customers, and then to display an infoWindow when you click on one of the markers.
problem is anytime you click on the marker it re-renders the map from scratch, i know this has to do with the the reactivity of the Session variable being set when the infoWindow is being clicked.
is there any way avoid the map being re-rendered when the session variable is changing?
thanks.
below is the JS and template im using in my project.
<template name="customers_map">
{{#constant}}
<div id="mapWrapper">
<div id="map-canvas"></div>
</div>
{{/constant}}
</template>
the code for making the google maps and markers.
Template.customers_map.rendered = function() {
$("#map-canvas").height("400px");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
Session.set("myLat", p.coords.latitude);
Session.set("myLng", p.coords.longitude);
});
}
Deps.autorun(function(){
var mapOptions = {
center: new google.maps.LatLng(Session.get("myLat"), Session.get("myLng")),
zoom: 15,
zoomControl: true,
zoomControlOptions: {style: google.maps.ZoomControlStyle.SMALL},
streetViewControl: false,
mapTypeControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.SMALL
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var infowindow = new google.maps.InfoWindow({
content: Template.customers_infoWindow()
});
Customers.find().forEach(function(customer) {
if (customer.loc != null) {
var geo = customer.geoLocation();
var marker = new google.maps.Marker({
position: new google.maps.LatLng(geo.lat, geo.lng),
title: customer.name(),
icon:'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
Session.set("customerId", customer._id);
infowindow.open(map,marker);
});
} else {
console.log(customer.name() + " has no geoLocation");
};
});
});
};
the infoWindow template
<template name="customers_infoWindow">
<h1>{{record.name}}</h1>
</template>
and the js for the infoWindow template
Template.customers_infoWindow.record = function() {
return Customers.findOne({_id: Session.get("customerId")});
}
If you create a global googlemaps object, you can access its properties from anywhere. This article has a nice example of doing this.
The overall gist is:
Create a googlemaps class with an initialize method. At the end of the initialize method, set a session variable for your map's existence. ( Session.set('map', true);)
Call create a googlemap object by calling the googlemap init method from within Template.customers_map.rendered.
It's a bit difficult to be sure without having a running version in front of me, but I think this is essentially because you have all your code in one big Deps.autorun block. Clicking one of the markers is changing the Session variable customerId, which will cause customers_infoWindow to re-render (as it's clearly a dependency), but I'm sure this is the intended behaviour.
However, since you're declaring var infoWindow in your Deps.autorun block to have an instance of that template as one of its properties, I think that changing customers_infoWindow will actually invalidate the entire Deps.autorun calculation, which means the whole block will be executed again, including the var map = new google.maps.Map(...) line, which will essentially re-render the map (even though it doesn't re-render that actual div element that contains it).
So, I would suggest splitting your code into separate Deps.autorun blocks, and making sure that anything in the same block should be re-run at the same time - clearly, this means that the Google Maps initialisation code and the infoWindow handler should be in separate blocks.
To reiterate, I think that's what's going on, but you'll have to try it and let me know...

Link back to Google from API Marker

I'm using the Google Maps API v3 to generate some minimaps. I have one custom marker in a small map with controls hidden. This works great. Now, I'd like to add a link so that clicking this marker will open the full Google Maps with this location selected. Seems obvious.
I'm creating a marker like this.
var pin = new google.maps.LatLng(myLat,myLong);
var marker = new google.maps.Marker({
position: pin,
map: map,
title:"Hello World"
});
This seems like it should be obvious, what am I missing? Do I need to construct my link and assign it myself?
This should work (not tested):
var pin = new google.maps.LatLng(myLat,myLong);
var marker = new google.maps.Marker({
position: pin,
map: map,
title:"Hello World"
});
google.maps.addListener(marker, "click", function() {
window.location = "https://maps.google.com/maps?ll="+pin.toUrlValue;
});
Working example (built on an existing example, not from the above code)
Ended up finding the answer thusly:
google.maps.event.addListener(marker, 'click', function() {
window.open("https://maps.google.com/maps?ll="+pin.toUrlValue(),'_blank');
});

Google Map API in WordPress without a plugin?

I'm looking to simply add a google map using google maps api to one of my pages in WordPress. Is there a simple way of simply copy and pasting the "Hello, World" google maps code somewhere to have the map displayed on a page?
thanks
Yes, there's no need for a plugin for something like this. First of all you would include the Google maps script in header.php or you could enqueue it;
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
Then I normally add the following in header.php - this adds conditional code to the tag for the page containing the map only (in this case page 374);
<body <?php if (is_page(374)) { echo 'onload="initialize()" onunload="GUnload()"'; } ?>>
And then I would create a custom template for the contact page (as that's the page the map is normally on) and in the template for that page include something like the following. Yes, it's probably a bit long for a code sample but I'm just giving you a real example which contains an animated marker which can be clicked on to show your client's address. You could change the inline dimensions to suit your design, and you can also offset the map so the marker isn't right smack in the middle of it.
<div id="contact-content">
<script type="text/javascript">
function initialize() {
var leeds = new google.maps.LatLng(53.80583, -1.548903);
var firstLatlng = new google.maps.LatLng(53.80583, -1.548903);
var firstOptions = {
zoom: 16,
center: firstLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_leeds"), firstOptions);
firstmarker = new google.maps.Marker({
map:map,
draggable:false,
animation: google.maps.Animation.DROP,
title: 'Your Client',
position: leeds
});
var contentString1 = '<p>The Address<br />Of your client<br />in<br />here</p>';
var infowindow1 = new google.maps.InfoWindow({
content: contentString1
});
google.maps.event.addListener(firstmarker, 'click', function() {
infowindow1.open(map,firstmarker);
});
}
</script>
<div class="map">
<div id="map_leeds" style="width: 600px; height: 600px"></div>
</div>
</div>
If anyone else does it a different, better way then I'd be keen to see it, but I've used this on loads of sites and it works really well.

Google maps KmlLayer times out and InfoWindow not showing

I have a google map embedded in a site that loads a kml file at https://www.getstable.org/who-can-help/therapist-map-kml using KmlLayer. Sometimes the map doesn't load up, I presume because google maps has a strict timeout, and often some of the pins on the map aren't clickable but some are with no clear reason why. Does anyone know what the timeout limit is on kmlLayer and how to increase it? Also is there any reason why sometimes some of the pins aren't clickable (ie no InfoWindow appears when you click a pin and the cursor doesn't change to a hand)?
Here's the code that shows it (some of the fields are templated):
<div id="map_canvas" style="width: 856px;height: 540px;">Loading...</div>
<script type="text/javascript" src="{protocol}://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var the_map = {
options : {
zoom:{embed:zoom_level},
center:new google.maps.LatLng({embed:latitude},{embed:longitude}),
mapTypeId: google.maps.MapTypeId.ROADMAP
},
geocoder : null,
map : null,
init : function() {
this.geocoder = new google.maps.Geocoder();
$('#map_canvas').delegate('a', 'click', function(event) {
window.location.href=$(this).attr('href');
return false;
});
},
load_map : function() {
this.map = new google.maps.Map(document.getElementById("map_canvas"), this.options);
query = encodeURI('{site_url}{embed:map_url}');
var ctaLayer = new google.maps.KmlLayer(query,{
preserveViewport:true
});
ctaLayer.setMap(this.map);
}
}
$(document).ready(function() {
the_map.init();
the_map.load_map();
});
</script>
The Google Servers have an unspecified timeout, but testing shows it to be 3-5 seconds. This timeout is not something you can affect. The solution is to make your server respond faster. This issue almost always comes down to a file that is too big (yours isn't) or from dynamically generating the KML. You need to optimize this and that may mean finding a way to create a static KML file.
Features that are not clickable are almost certainly a problem with your KML. You can validate your KML to check for this:
Feed Validator
KML Validator
You can also test your KML by loading it at maps.google.com.

Pegman has disappeared from my map

For as long as I can remember, the street view pegman has appeared on my map. Today, I noticed that he doesn't appear (although if you know where to mouse over to grab him, you can still get a streetview happening). My zoom control has similarly disappeared (but is still there if you know where to mouse for it) but not on mobile devices where it seems to display just fine.
My first guess is that this is a bug in the Maps API that's been introduced recently. But specifying v=3.4 in the URL for the API doesn't correct the issue.
Am I doing something wrong? If not, is there a workaround?
Here's how I create the map:
<script type="text/javascript">
var lat=<?php echo $lat; ?>;
var lon=<?php echo $lon; ?>;
var initialZoom=<?php echo $initialZoom; ?>;
var mapTypeId = 'Custom Map';
var mapStyle = [{featureType:"administrative", elementType:"all", stylers:[{hue:"#dae6c3"},{saturation:22},{lightness:-5}]},
{featureType:"landscape", elementType:"all", stylers:[{hue:"#dae6c3"},{saturation:16},{lightness:-7}]},
{featureType:"road", elementType:"geometry", stylers:[{hue:"#ffffff"},{saturation:-100},{lightness:100}]}];
var styledMap = new google.maps.StyledMapType(mapStyle);
var mapType = new google.maps.ImageMapType({
tileSize: new google.maps.Size(256,256),
getTileUrl: function(coord,zoom) {
return "img/tiles/"+zoom+"/"+coord.x+"/"+coord.y+".png";
}
});
var map = new google.maps.Map(document.getElementById("map_canvas"),
{center:new google.maps.LatLng(lat,lon),
mapTypeId:google.maps.MapTypeId.ROADMAP,
zoom:initialZoom,
mapTypeControl:false});
map.overlayMapTypes.insertAt(0, mapType);
map.mapTypes.set(mapTypeId, styledMap);
map.setMapTypeId(mapTypeId);
</script>
I had recently added this CSS rule which was causing the problem:
img {
max-width: 100%;
}
Removing that rule fixed the problem.

Resources