Handling network disconnect while loading Google maps asynchronously - javascript

Trying to load the Google maps asynchronously so that the start of the HTML page is faster.
Have used the following code as mentioned in the link: https://developers.google.com/maps/documentation/javascript/tutorial#asynch. Section: Asynchronously Loading the API.
function initialize() {
var myOptions = {
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"), myOptions);
}
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;
Issues:
When the network is disconnected after the loadScript() function is invoked. Currently we do not find anyway to check the network connection is terminated & do appropriate error handling.
Even when the network is available some times the callback function 'initialize()' is never called.
Loading of google maps on mobile device is very slow even on a 3G network.
In both the cases mentioned above, we start a loading icon immediately after loadScript() is invoked. As initialize() is not called back it gets blocked in the loading icon for infinite time.
Kindly provide some pointers to handle the network disconnect & callback function not invoked issues.

The Maps API does not have a native way to handle this. Thankfully HTML5 does. Listening to the document.online / document.offline events is very effective and I have used it to solve this problem.
See https://developer.mozilla.org/en/DOM/document#Event_handlers
This is supported in at least iOS 5 and Android 2.3.
You could also use setTimeout to check that the API callback has occurred and handle it appropriately if not.

Related

Google Map API - 'google' not defined - MVC5 javascript

I get JavaScript "google is undefined" error.
I apologize if this question is similar to this but I am using it in a different setting, so this may be an MVC issue.
I use MCV5 website standard template and I put in the head of _layout.chtml main template:
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
This code goes into one of the views, for the account/index action:
<div id="map_canvas"></div>
<span id="result"></span>
<script>
var map = null;
var markersArray = [];
function initialize() {
var latlng = new google.maps.LatLng(13.73868, 1.07143);
var settings = {
zoom: 14,
center: latlng,
mapTypeControl: true,
scaleControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'white'
};
map = new google.maps.Map(document.getElementById('map_canvas'), settings);
google.maps.event.addListener(map, 'click', function (event) {
document.getElementById('result').innerHTML = 'Lat: ' + event.latLng.lat() + ' Lng: ' + event.latLng.lng();
});
}
window.onload = initialize;
</script>
Somehow the linked google js file does not seem to load by the time function initialize() runs and I get JavaScript "google is undefined" error in the first line of initialize() function.
Thanks for your help.
The only real point where MVC could be an issue is in the loading of your layout. Have you inspected the page source to ensure that the Google Maps API script is actually on the page? If it's not, then you just need to figure out why your view isn't utilizing the layout you think it should be.
If it is on page, then open the link to the JS file and ensure that it loads properly. Especially if you on a corporate network, sometimes firewalls or other security software may prevent certain scripts from loading properly. You'll need to work with your Infrastructure department if that's the case.
Also, watch your usage of SSL. If you're using SSL for the site you're loading this on, then this script won't load because it's coming over HTTP, not HTTPS. In general, it's always better to use the HTTPS version of external resources, as that should work whether your site is running on HTTPS or HTTP. Also, you can just make the URL protocol relative:
<script src="//maps.google.com/maps/api/js?sensor=false"></script>
Assuming it's not one of those annoying instances where the third-party uses an entirely different domain for SSL, it will then request either HTTP or HTTPS depending on what your site is using.

navigator.geolocation.getCurrentPosition freezing the webpage

I am building a phonegap application and I have one input element like this:
<input type="text" id="currLocation"></input>
And I have a Javascript code like this in bottom of the page:
$(document).ready(function(){
geocoder = new google.maps.Geocoder();
navigator.geolocation.getCurrentPosition(onSucc, onFail,{timeout: 10000, enableHighAccuracy: true});
}
To get the current location of a user. This code works fine, but the only problem I am facing is page freezes until getCurrentPosition() completes load(success or failure) and entire page displays as white. What I want is at-least DOM elements should display and this getCurrentPosition() should execute in background so UI won't freeze. How do I achieve this? I tried doing like this by calling those without functions in full bottom of the page:
<script>
geocoder = new google.maps.Geocoder();
navigator.geolocation.getCurrentPosition(onSucc, onFail,{timeout: 10000, enableHighAccuracy: true});
<script>
But I get below error:
Uncaught TypeError: Failed to execute 'getCurrentPosition' on 'Geolocation': The callback provided as parameter 1 is not a function
Can anyone please guide me in this?

Bing maps api works on pc but not mobile web app

I really hope someone can help with my problem. I have built a mobile web app http://ufa-ld-qa.azurewebsites.net/ (the QA site) with asp.net mvc4 using Bing Maps API for various functionality in the app. I am having problems with the directions module. When I view the site on my pc (Chrome and IE) it works fine and I see no errors but on mobile devices it is not working (but it did work fine yesterday when we launched to QA). I have used HTML5 geolocation (this may be the issue) to get user's location to allow them to get directions to a location. I will post my code below and if anyone could please help me it would be greatly appreciated. We have tested it on about 7 different mobile devices with different OS's and it doesn't work on any. Does anyone know if this is a Bing issue or my code below? Thanks so much in advance.
<script type="text/javascript">
var map = null;
var directionsManager = null;
var userLat = null;
var userLong = null;
var userPosition = null;
var latlng = new Microsoft.Maps.Location(#Model.latitude, #Model.longitude);
navigator.geolocation.getCurrentPosition(locationHandler);
function locationHandler(position)
{
userPosition = new Microsoft.Maps.Location(position.coords.latitude, position.coords.longitude);
}
function GetMap() {
// Initialize the map
map = new Microsoft.Maps.Map(document.getElementById("map"), { credentials: "Au_7giL-8dUbFkJ8zLjcQKy4dV2ftPfpMxQ0_sVBksoj4Y-1nBT00Z1oqUIU894_",
mapTypeId: Microsoft.Maps.MapTypeId.road});
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
}
function directionsModuleLoaded() {
// Initialize the DirectionsManager
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
// Create start and end waypoints
var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: userPosition });
var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: latlng });
directionsManager.addWaypoint(startWaypoint);
directionsManager.addWaypoint(endWaypoint);
// Set request options
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
// Set the render options
directionsManager.setRenderOptions({
itineraryContainer: document.getElementById('directionPanel'),
displayWalkingWarning: false,
walkingPolylineOptions: { strokeColor: new Microsoft.Maps.Color(200, 0, 255, 0) },
});
// Specify a handler for when an error occurs
Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
// Calculate directions, which displays a route on the map
directionsManager.calculateDirections();
}
function displayError(e) {
// Display the error message
alert(e.message);
}
</script>
A couple of things to try. First ensure that your app is allowed to access the users location. Most mobile platforms require you to mark that the app requires access to the GPS in the manifest. Another thing to look into is the possibility that the userLocation isn't populated before your callback for the directions manager is called. It's possible that the GPS takes a little longer on the mobile device to find the users location and as such the directions loaded function is firing before the users location is set, thus passing in a null starting . You might find it useful to have a flag to indicate that the directions manager has loaded and a simple function that runs after setting the flag and also runs after setting the use location that checks that both the directions manager has loaded and the user location has been set and then calls your directions loaded function.
My Windows Phone 8 App is experiencing similar behavior. (Nokia 920)
http://bing.com/maps/default.aspx?cp=47.677797~-122.122013&lvl=12
When the Website preference is set to 'desktop version' the map renders correctly.
When the Website preference is set to 'mobile version' the map renders incorrectly.
Just started happening about a week ago !

Real time GPS Tracker on JUST HTML / JS and Google Maps to be run on a handphone? Is it possible?

I have read up on GPS Real time tracking and found out several things about it, mostly requiring PHP, zope and a database to store the incoming data. Some other methods uses ajax with relations to PHP.
As regards to my question, is it possible to do so with just html and JS, using markers or anything else to populate the Google Map when you move anywhere in the city? Need some help on this, Thanks!
Yes, it is possible. Most browsers in the latest smartphones have implemented the W3C Geolocation API:
The Geolocation API defines a high-level interface to location information associated only with the device hosting the implementation, such as latitude and longitude. The API itself is agnostic of the underlying location information sources. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs, as well as user input. No guarantee is given that the API returns the device's actual location.
The API is designed to enable both "one-shot" position requests and repeated position updates, as well as the ability to explicitly query the cached positions.
Using the Geolocation API to plot a point on Google Maps, will look something like this:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var point = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: point,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Place a marker
new google.maps.Marker({
position: point,
map: map
});
});
}
else {
alert('W3C Geolocation API is not available');
}
The above will only gather the position once, and will not auto update when you start moving. To handle that, you would need to keep a reference to your marker, periodically call the getCurrentPosition() method, and move the marker to the new coordinates. The code might look something like this:
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = null;
function autoUpdate() {
navigator.geolocation.getCurrentPosition(function(position) {
var newPoint = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
}
else {
// Marker does not exist - Create it
marker = new google.maps.Marker({
position: newPoint,
map: map
});
}
// Center the map on the new position
map.setCenter(newPoint);
});
// Call the autoUpdate() function every 5 seconds
setTimeout(autoUpdate, 5000);
}
autoUpdate();
Now if by tracking you mean that you should also store this information on a server (so that someone else could see you moving from a remote location), then you'd have to send the points to a server-side script using AJAX.
In addition, make sure that the Google Maps API Terms of Use allow this usage, before you engage in such a project.
UPDATE: The W3C Geolocation API exposes a watchPosition() method that can be used instead of the setTimeout() mechanism we used in the above example.

Google Maps rendering locally but not in live environment

I have a page that renders a simple google map for a specified location. This map renders without any problems at all when I run it locally on localhost, however, when I deploy this code to our live web servers (using our LIVE google API key for the appropriate domain) it fails to render, and upon putting a series of alerts within the javascript on the page, it appears that the 'Initialize' method (which should be called within body onLoad) is not being called.
When I view the HTML source that is rendered on the live server it appears exactly as per the local version of the site (including the call to initialize() within the body onLoad event), albeit with the different maps API key.
I have output the host (alert(window.location.host);) to ensure that the key I generated via the google maps api site, corresponds exactly to the live server, which it does.
Does anyone have any ideas why it would be working locally but not when deployed to the live servers? The live site is hosted on 2 load-balanced web servers.
This is the javascript that is rendered:
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAA-BU8POZj19wRlTaKIXVM9xTz76xxk4yAELG9u79oXrhnLTB5NRRvAZ-bkKn1x8J68nfRTVOIWNPJEA" type="text/javascript"></script>
<script type="text/javascript">
var map;
var geocoder;
alert(window.location.host);
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("businessMap"));
map.setUIToDefault();
geocoder = new GClientGeocoder();
showAddress('St Margarets Street SW1P 3 London');
}
}
function showAddress(address) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
// Address could not be located.
jQuery('#googleMap').hide();
} else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
var html = 'Address info for the marker';
marker.openInfoWindow(html);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
}
}
);
}
</script>
Any help would be much appreciated.
Thanks.
I've located the problem. It was some conflicting javascript related to Facebook Connect that was calling an FB Connect related page on window.onload, therefore not calling the initialize function within the body onload event.
I should have noticed this conflicting javascript earlier!

Categories

Resources