Googlemaps API very slow when initialized from window.onload - javascript

To avoid an ie 7/8 "unspecified error", I recently moved the initialization logic for a JSON powered GoogleMaps v3 implementation from inline following $(document).ready to within an event function triggered from window.onload(). Now, what was once a very fast load is now taking 15-20 seconds + to load. I understand that there are some subtle differences between oninit and onload, but this seems extreme. Any thoughts?
$(document).ready(function(){
var branchitems=[];
var markers=[];
var map="";
window.onload = function() {
var latlng = new google.maps.LatLng(59.5, -100.68);
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
PopulateMap(map);
}
function PopulateMap(map){
... my logic for the JSON portion of the map ...
};

window.onload is the right place to put this if you're loading the API synchronously, otherwise your code may execute before the Maps API has downloaded.
If this is taking 10 - 15 seconds then it is likely that you are loading a bunch of other resources as well. window.onload won't execute until everything has finished downloading (e.g. all scripts in script tags).
One solution may be to load Maps API V3 asynchronously (see: http://code.google.com/apis/maps/documentation/javascript/basics.html#Async). You can then start constructing your map as soon as the API has loaded.
An alternate solution is to asynchronously load anything that you don't need to be ready as soon as a user visits the site, or to load your resources from faster locations (e.g. load jQuery from the Google CDN instead of from your own server).

Related

Streetview Gives blackbox with Navbuttons, no street image, when loading

I'm using react to load streetview into a component I get this :
As we can see - the map component loads fine, and the streetview component seems to load fine, except that the image behind it (the actual street view) isn't loaded.
The error reported is :
**
Uncaught TypeError: Cannot read property 'toString' of undefined in
maps.googleapis.com/imagery_viewer.js:299
**
When I run similar code in straight-up HTML, this works ... sometimes ... often I get no returned image
I've isolated the code into a special function triggered with a large setTimeout() call so that the document load time is not to blame. Indeed, using watches and breakbpoints, we can see that the DIVs are loaded and accessible at run time.
handleLoad: ->
options = {
addressControl: true
fullscreenControl: true
panControl: true
pov: this.props.image.pov
visible: true
zoomControl: true
}
if this.props.image.pano
options.pano = this.props.image.pano
else if this.props.image.position
options.position = new google.maps.LatLng this.props.image.position[0], this.props.image.position[1]
if this.props.image.position
pos = new google.maps.LatLng this.props.image.position[0], this.props.image.position[1]
else
pos = {lat: this.props.entryLatitude, lng: this.props.entryLongitude};
options.key ='XXXX - GOOGLE MAP API KEY GOES HERE - XXXX';
this.map = new google.maps.Map(this.mapDiv, { center: pos, zoom: 14, visible:true } , streetViewControl: false);
this.panorama = new google.maps.StreetViewPanorama this.panoramaDiv, options;
this.map.setStreetView(this.panorama);
Any suggestions what could be causing this problem ?
This known black street view panorama issue can be cache or cors related. I suggest you first try ruling both of them out. E.g. see https://support.google.com/maps/thread/6166296?msgid=8836199
It may also be due to a third-party library bug or conflict. E.g. if you're using mootools or prototype.js check out these threads:
Mootools breaks Google maps streetview - black screen
https://issuetracker.google.com/issues/139252493
Another potential reason could be that your lat/lngs are far away from the roads where the street view imagery is available. Have a look at this great answer to related question Google map JS API "StreetViewPanorama" display black screen for some address
Let us know if any of the linked solutions work for you; otherwise please provide a codesandbox or stackblitz that reproduces the issue and I'll be happy to investigate further.

Map in Framework 7

I am trying to load my map in framework 7 but I am unable to do that. The error I am getting is google is undefined.
Below are my codes
JavaScript code
CascadingApp.onPageInit('admin', function(page) {
initialize();
});
function initialize() {
var map = null;
var latlng;
latlng = new google.maps.LatLng(37.4419, -122.1419);
var options = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), options);
}
HTML CODE
<div id="map" style="height:400px; width:1200px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?key= AIzaSyAWzZ-1BPmaWKFT0du3cis82mj9Y5ljIgk&callback=initMap" async defer></script>
Does not load map in the page.
Add google api script<script src="https://maps.googleapis.com/maps/api/js?key= AIzaSyAWzZ-1BPmaWKFT0du3cis82mj9Y5ljIgk&callback=initMap" async defer></script> in your index.html file. Currently api is present admin.html template. So when the
admin view is load
CascadingApp.onPageInit('admin', function(page) {initialize();}); at that time google api is not full loaded i.e asynchronous behavior and throw error google not defined. So simply put google api in your index.html page rest is fine.
Hope it helps you !
I added the Google script at the bottom of my index.html but without the callback function.
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
Next, in my app.js script, declare the variable map as global and create the following function to init the map when the page is fully loaded :
$$(window).on('load', function(e) {
initMap();
});
Define the same initMap function inside app.js and remember set a style to map div (width and height at least).
Hope helpful to you ;-)

Create Element to insert an API

I want to create a div using javascript to put my google map into.
It creates a div, but doesnt put the map api into it. Please help.
You need to make sure the Google Maps API script has loaded before running your code. Currently, you are trying to build the map before the browser has downloaded the map API.
The simplest way to fix this is to change your HTML to this:
<script src="https://maps.googleapis.com/maps/api/js?key="Entered key here deleted it for stackoverflow"&callback=initMap">
<script src="javascript.js"></script>
You could also remove the Google Maps script tag and load it dynamically in javascript.js using jQuery’s $.getScript() or with plain JS using https://github.com/filamentgroup/loadJS, running your code as the callback.
initMap is firing when the script loads, but create isn't getting called until you click that p tag. Here's a way to get around that issue, but still wait for the script to load before allowing clicks:
var mapready = false, createcalled = false;
function create()
{
createcalled = true;
if(mapready){
var newDiv = document.createElement("map");
newDiv.id = "map";
newDiv.style.border="solid";
document.body.appendChild(newDiv);
var uluru = {lat: 54.278556, lng: -8.460095};
var map = new google.maps.Map(document.getElementById('map'), {zoom: 16,center: uluru});
var marker = new google.maps.Marker({position: uluru,map: map});
}
}
function initMap()
{
mapready = true;
if(createcalled) create();
}
In this scenario, if the user clicks the p tag before the map is ready, the create function will fire as soon as the map API finishes loading.

Google Maps inside Ember.js

I've successfully managed to get Google Maps rendering on my main page. I'm using the same technique for one of my inner pages.
var MapView = Ember.View.extend({
layoutName: 'pagelayout',
didInsertElement : function(){
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(this.$("#map").get(0),mapOptions);
this.set('map',map);
},
redrawMap : function(){
var newLoc = new google.maps.LatLng(this.get('latitude'), this.get('longitude'));
this.get('map').setCenter(newLoc)
}.observes('latitude','longitude')
});
However, it doesn't render. If I change it like so, it works but takes over the base html element.
this.$().get(0) /**from this.$('#map').get(0)**/
I'm quite stumped. Thinking that the problem might be that didInsertElement was being trigger way too early (I've understood it that the entire DOM for this View will be available when this event fires), I've tried setting up a afterRender listener and triggered the map load but that fails too. I've triple checked that the div exists.
Can someone please help me with this?
I ran the Google Maps init code from my console and found that the map did load so it seems to be an issue with how didInsertElement works with my setup. My understanding what that didInsertElement was called when the View was in the DOM but perhaps because I'm using layouts , it works differently.
I solved it by calling a separate view from within the div itself
{{#view "map"}}
and by creating a new View for the map.
var MapView = Ember.View.extend({
/**
Same as before
**/
});
This is just my solution that may be useful to others facing the same problem. If someone has a better solution, please add it so that I can verify and upvote it.
The this.$() might not be available as the view might not have rendered yet. Try wrapping it in a Ember.run.next call to delay the execution in the next run loop cycle:
didInsertElement: function() {
Ember.run.next(this, function() {
// your code
});
});

Adding Geolocation to Google Places Library

We're trying to build an app that allows users to view places around their current location.
You can see the Google Maps API & the Google Places Library functioning here, but not as one: http://www.blazingsasquatch.com/geo/index4.html
You'll notice the button "show me my loc" pulls your current location and the map is showing an arbitrary location in Boston with places nearby.
We've created variables for both the longitude and latitude and we've attempted to pass those variables directly into the "pyrmont" location variable but we've had no luck.
Initially we tried setting the "pyrmont" location using following, also with no luck:
google.maps.LatLng(position.coords.latitude, position.coords.longitude);
So how can we get the current location populated?
var pyrmont = new google.maps.LatLng("CURRENT LOCATION HERE");
Will it accept a variable or an integer only?
initialize will be called before the callback of navigator.geolocation.getCurrentPosition() , so you cannot use the result in initialize() .(you may view getCurrentPosition as a asynchronous request)
Invoke the action(creation of the marker and places-request) inside the callback of getCurrentPosition()
See a working demo: http://jsfiddle.net/doktormolle/C5ZtK/
The LatLng constructor takes two floating point numbers, like so:
pos = new google.maps.LatLng(-34.397, 150.644);
After reviewing the source code, it seems the problem is another one: the anonymous callback function you are passing to getCurrentPosition() is called when the geographic location is found, which can take some time (especially using GPS and such). initialize() is called when the page is loaded, which is sooner, so place is not set at this time (besides, it's not visible in initialize() since it's not a global variable, but never mind that). So you have to move the stuff you're currently doing in initialize() to the callback function you are passing to getCurrentPosition(). Then, you can use
var pyrmont = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

Categories