Magento 1.9 does not render Google Maps Api in template
-
13-12-2020 - |
Question
I am trying to render Google Map on my custom page. I have template that renders smth but it does not render map.
But I've discovered strange thing (for me) if echo smth in controller between
$this->loadLayout(); echo 'asd'; $this->renderLayout();
IndexController.php
class Stas_Offices_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->loadLayout();
echo 'asd';
$this->renderLayout();
}
}
Template: officesmap.phtml (MY_API_KEY = my google api key)
<h1>asd</h1>
<div style="height: 100%" id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.7413549, lng: -73.9980244},
zoom: 13
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&v=3&callback=initMap">
</script>
Layout: app/design/frontend/base/default/layout/stasoffices.xml
<layout version="0.1.0">
<offices_index_index>
<reference name="content">
<block type="stasoffices/officesmap" name="stas.offices.officesmap" template="stas/offices/officesmap.phtml"></block>
</reference>
</offices_index_index>
This is what I see when I echo'123';
in Controller
And this is when there is no echo'123';
in Controller
The only difference I understood that scripts with API include earlier when echo'123';
in Controller
Could anyone please explain me why this happens and how to render map without this ugly "echo" in controller! Thank you.
Solution 2
I tried this
<div style="height: 400px" id="map"></div>
And now it works perfect.
Problem was in CSS height: 100%
.
OTHER TIPS
In our project we use map without any conflicts, Could you please try to cover your map initialization function by load event like
window.onload = function () {
}
And delete async call of your map.
This is code from our module where map works perfectly -
<script language="javascript" type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true&libraries=places<?php echo $this->getApiKey() ?>"></script>
<script type="text/javascript">
window.onload = function () {
AmLocation = new AmLocator('<?php echo $this->getUrl('amlocator/index/ajax').$this->getQueryString(); ?>',<?php echo $this->getGeoUse() ?>);
AmLocation.Amastyload(<?php echo $this->getJsonLocations() ?>);
}
</script>
At the Load function we just init map and do some module logic.
initializeMap: function() {
this.infowindow = [];
this.marker = [];
var myOptions = {
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map = new google.maps.Map(document.getElementById("amlocator-map-canvas"), myOptions);
},
Feel free if you have any questions. If you still have this issue at your project please provide screenshot of the browser console.