JQuery Mobile and Google Maps Not Rendering Correctly - google-maps

I am simply trying to display a google map within a jquery mobile page. If I load the page directly it works. However, if I navigate to the page from another page it only renders a single map tile. At first glance it would appear that my issue was similar to https://forum.jquery.com/topic/google-maps-inside-jquery-mobile
However, I was already performing my initialization within the 'pageinit' event and my map div has a set width and height.
I have seen http://code.google.com/p/jquery-ui-map/ but I would rather not use a (another) third party plugin if at all possible.
Here's what my page looks like:
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="cordova-1.6.1.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.1.0.min.css" />
<script src="jquery-1.7.1.min.js"></script>
<script src="global.js"></script>
<script src="jquery.mobile-1.1.0.min.js"></script>
</head>
<body>
<div id="mapPage" data-role="page">
<style type="text/css">
html
{
height: 100%;
}
body
{
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas
{
height: 100%;
}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=***API_KEY_REMOVED***&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var height = $(window).height() - 50;
var width = $(window).width();
$("#map_canvas").height(height);
$("#map_canvas").width(width);
var myLatlng = new google.maps.LatLng(39.962799, -82.999802);
var myOptions = {
center: myLatlng,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
//alert($(map.getDiv()).width());
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: ""
});
google.maps.event.trigger(map, 'resize')
}
$("#mapPage").live('pageinit', function () {
initialize();
});
</script>
<div data-role="header" id="menuHeader">
<a href="MenuDialog.htm" class="menuLink" data-role="none" data-rel="dialog">
<img class="headerIcon" style="height: 40px; border-right: 1px solid #333333; padding-right: 5px;"
id="MenuIcon" src="images/menuIcon.png" /></a>
<p>
Loc
</p>
</div>
<div data-role="content">
<div id="map_canvas" style="margin-top: 50px;">
</div>
</div>
</body>
<html>
Thanks in advance for you help.
Update:
After some experimenting I added the following delay to my resize event:
setTimeout(function() {
google.maps.event.trigger(map,'resize');
}, 500);
This seemed to fix the issue. Hopefully this helps someone else.

I read on a website that if you have this problem it's beacuse the dom isn't totally loaded when you initialize your google map.
You must add this in your code:
$( document ).bind( "pageshow", function( event, data ){
google.maps.event.trigger(map, 'resize');
});
It works for me. It's maybe brutal to resize at every page you show but ... it works.

You have <html> and <body> at 100% size, but not the <div>s in the hierarchy between <body> and <div id="map_canvas">.
Try adding those to your CSS as well (the content one will need an id).
You may also need to ensure that the API knows the size of the map <div> by triggering a resize event when everything is ready. Showing only a single tile is a classic symptom of the API getting it wrong (and generally assuming it has zero size).

Instead of firing a resize, I solved this by wrapping my js in a 'pagecreate' event... like this:
$(document).on('pagecreate', '#map', function() {
var mapOptions = {
center: new google.maps.LatLng(40.773782,-73.974236),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
});

I think the right approach would be to trigger the event when partial tile is loaded once. Below code snippet will help you in achieving that.
google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
google.maps.event.trigger(map,'resize');
});

I found the issue for me was that JQuery mobile uses Ajax to load the pages. I am not sure if it is the best practice but I simply forced it to load my map page normally by putting the following code in the anchor tag:
data-ajax="false"

Related

Google Map didn't work after following instructions from Google Map site

I followed the instructions from https://developers.google.com/maps/tutorials/fundamentals/adding-a-google-map
When I run it at Netbeans 8.0.2, only the gray div showed up, no map was shown.
This is my code:
<html>
<head>
<title>Practicing Google Maps</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<script src="https://maps.googleapis.com/maps/api/js">
function initialize() {
// The Map object constructor takes two arguments:
/*
* A reference to the div that the map will be loaded into. We use
* the JavaScript getElementById function to obtain this:
*/
var mapCanvas = document.getElementById('map-canvas');
/*
* Options for the map, such as the center, zoom level, and the map type.
* There are many more options that can be set, but these three are required:
*/
var mapOptions = {
center: new.google.maps.LatLng(44.5403. -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.SATELLITE
}
var map = new google.maps.Map(mapCanvas);
}
/*
* Add an event listener to the window object that will call the initialize function
* once the page has loaded. Calling initialize before the page has finished loading
* will cause problems, since the div it's looking for may not have been created
* yet; this function waits until the HTML elements on the page have been created
* before calling initialize.
*/
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas">
</div>
</body>
</html>
What did I miss? I even comment Google's instructions so I will not miss a thing but still, Google Map didn't show up.
Thank you.
You appear to be missing the closing </script> after loading the Google maps library. And then an opening <script> tag for your code. You also have a few typos, corrected below:
center: new google.maps.LatLng(44.5403, -78.5463),
You've also left out mapOptions when initializing the map:
var map = new google.maps.Map(mapCanvas, mapOptions);
And finally, your div should have some dimensions.
Working code below:
function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var mapOptions = {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.SATELLITE
}
var map = new google.maps.Map(mapCanvas, mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div style="height:200px; width:200px" id="map-canvas">
Try adding a dimension to your map-canvas div. This usually works.
<div id="map-canvas" style="width:100%; height:100%;"></div>

Can't change color of KML Polygon, Style tag shows as invalid

I have a KML file I'm using google sites to host. The link is working in my code, because I can see the map as an overlay. But when I put any style in the KML, the page seem to ignore it. I tried to change it to yellow, but I only get the default blue. The KML has polygons with inner and outer boundaries. The code is being views in my editor (Coda 2). The map shows, and it's in the right place, but it's not the right color. Is there a way for me to change the color? see code below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Coverage Map</title>
<style>
html, body, #map-canvas {
height: 80%;
width: 80%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
function initialize() {
var chicago = new google.maps.LatLng(37.09024, -95.712891);
var mapOptions = {
zoom: 5,
center: chicago,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'https://sites.google.com/site/dmckmls/home/kml/Sprint.kml'
});
ctaLayer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Any ideas?
I changed the name of the file. I read about that somewhere as well for the change. That's rather annoying on google's parts. Such a powerful tool and they can't update the file because they have to cache it for performance sake. Thanks everyone for the help.

Insert google map showing my current location

I am traveling globally and need to insert a Google map on my web page that shows my current position (not the position of the reader) so that others can see where I am.
Does anyone have a straightforward solution to do this. I know how to use My Places to create maps and insert in my pages, but have avoided having to get involved in using the Maps API so far. I have some knowledge of HTML and Javascript, but it is minimal so would rather avoid this if I can.
Does anyone have a solution to this?
Further to my answer over at your other question you may find bits of this example useful: - hypoCampus
The little blue man/person/icon follows your location. If you scroll the maps away you can then press the static blue map-control man to re-center on your location. When you're moving (throttled location update is changing) the icon is walking otherwise it is standing.
(There's a bug with Manifest - "display" : "standalone" at the mo Chrome bug)
Hopefully Firebase have committed to bypassing the speed-humps of W3C/IETF and will give us ServiceWorker Background Geolocation tracking very soon.
you must tell to map your current location. for that you must get your location Latitude and Longitude for show that by maps.
get that by :
http://maps.googleapis.com/maps/api/geocode/xml?address=+" + MapAddress + "&sensor=false
try this html code in your page. str_lat and str_lng are your location :
<head>
<meta name='viewport' content='initial-scale=1.0, user-scalable=no' />
<style type='text/css'>
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type='text/javascript' src=https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=false>
</script>
<script type='text/javascript'>
function initialize() {
var myLatlng = new google.maps.LatLng(str_lat,str_lng);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:'Location!'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id='map-canvas'/>
</body>
</html>;
See Here https://developers.google.com/maps/documentation/javascript/tutorial
and see this code for judging your skills don't worry about new terms they are explained in the link above
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=SET_TO_TRUE_OR_FALSE">
</script>
<script type="text/javascript">
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-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>

Google Maps API v3: Gray Box, no map

As part of a much bigger project, we're trying to get a Map on a site using Google's Map API v3. I have followed the simplest steps that Google has laid out, I've tried copying code outright from other working maps. But no matter what I do, all we get is a gray box and no map.
Using Firebug, I can see the information trying to populate the map, but it is simply not displaying. I've tried jquery, jquery libraries specifically made for google maps, nothing is working. I have been up and down the internet and all through google's api help files. Plus, the problem is not local as I've uploaded the file to multiple servers and tested it on multiple browsers and computers. Nothing is working.
At this point it's got to be something stupid that I'm overlooking. Here's my code.
<!DOCTYPE html>
<html>
<head>
<title></title>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?&sensor=true">
</script>
<script type="text/javascript">
function load()
{
var mapDiv = document.getElementById("map");
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions =
{
//zoom: 8,
center:latlng,
//backgroundColor: '#ff0000',
mapTypeId: google.maps.MapTypeId.ROADMAP,
imageDefaultUI: true
};
var map = new google.maps.Map(mapDiv, mapOptions);
function createMarker(point, text, title)
{
var marker =
new GMarker(point,{title:title});
return marker;
}
}
</script>
</head>
<body onload="load()">
<div id="map" style="width: 800px; height: 400px;"></div>
</div>
</body>
</html>
This works for me. You simply have to set zoom parameter:
UPDATE (by #user2652379): You need to set BOTH zoom and center options. Just zoom does not work.
<!DOCTYPE html>
<html>
<head>
<title></title>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</script>
<script type="text/javascript">
function load()
{
var mapDiv = document.getElementById("map");
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions =
{
zoom: 8,
center:latlng,
//backgroundColor: '#ff0000',
mapTypeId: google.maps.MapTypeId.ROADMAP,
//imageDefaultUI: true
};
var map = new google.maps.Map(mapDiv, mapOptions);
// map.addControl(new GSmallMapControl());
// map.addControl(new GMapTypeControl());
// map.addMapType(ROADMAP);
// map.setCenter(
// new GLatLng(37.4419, -122.1419), 13);
}
</script>
</head>
<body onload="load()">
<div id="map" style="width: 800px; height: 400px;"> </div>
</body>
</html>
Another case is when map container is hidden at the moment you initialize the map. E.g. you are doing it inside bootstrap show.bs.modal event, instead of shown.bs.modal
I had the same issue and came across a lot of topics on stackoverflow but none of them had the working solution for me. I eventually found out it was caused to a line of css I had added.
All the elements in the map inherited a
overflow:hidden;
By adding the following line to my CSS it was fixed
#map * {
overflow:visible;
}
I would like to add a quick comment to this since I had the same problem with the zoom parameter set.
I found out that the problem was my theme's css. In my base theme I had the following CSS:
img, embed, object, video {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}
This messed up the rendering of the map and after I removed it, my map renders just fine.
Also beware of having an invalid latitude or longitude value for the map center or your markers. For example, this fiddle shows the Grey Map Of Death because the map center is at latitude 131.044 which is invalid (not from +90:-90).
function initMap() {
var uluru = {lat: 131.044, lng: -25.363};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
In my case, I was working on a map with vue and a modal in the iview library; and during the first render it worked, but any other render displayed the grey screen of death. I fixed the issue by setting a timeout function to display the map after 50 ms to give the modal enough time to render and be visible.
//Time out is crucial for the map to load when opened with vue
setTimeout(() => {
this.showMap(id);
}, 50);
The above example was an earlier fix and a quick hack, i have realized all you need to do is wait for the next tick, on vue you can achieve this by
async mounted(){
await this.$nextTick()
this.showMap(id)
}
or if you are not comfortable with async await you can try the callback option
mounted(){
Vue.nextTick(function () {
this.showMap(id)
})
}
I had the same issue. i was using google maps in Jquery Accordion and when i expand the div the map only consisted a grayed area. I was able to solve this issue by triggering a click event on the specified accordion heading and setting the map container to visible.
Script:
<script type="text/javascript">
var map;
function initMap(lat, lng) {
var myCenter = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: myCenter
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function ViewMap() {
var latlng = document.getElementById('<%=txt.ClientID%>').value.split(','); // This is where my latlng are placed: 25.12312,55.3212333
$("#showmap").show();
// Sorry for mixing up Jquery and javascript.
initMap(latlng[0], latlng[1]);
}
</script>
ASPX File/Html Markup:
<h3 id="lMap" onclick="ViewMap();"><i class="fa fa-map-o" onclick="ViewMap();"></i>Location Map</h3>
<div style="height:auto" id="showmap">
<div id="map" style="width: 850px; height: 550px; overflow: visible"></div>
</div>
I realise this is an old thread, but this may help someone in the future.
Struggled with this for hours, but after discovering that the Google Map is rendered with a grey box overlay if the map is rendered while not being visible, I used a bit of jQuery to make my application only instantiate and render the map if the map is visible, like such:
if ($("#myHomeMapHolder").is(":visible")) {
if (homemap == null) {
homemap = new google.maps.Map(document.getElementById("myHomeMapHolder"), myOptions);
google.maps.event.addListener(homemap, 'click', function (event) {
placeHomeMarker(event.latLng);
});
} else {
homemap.setCenter(myLatlng);
}
if (homemarker == null) {
homemarker = new google.maps.Marker({
position: myLatlng,
map: homemap,
title: "Home"
});
} else {
homemarker.setPosition(myLatlng);
}
}
And voila, my map is only rendered if the map holder is visible, so it never renders with a grey box.
For anyone wondering, myHomeMapHolder is a div which the map sits inside.
In my case, someone had dropped this little prize in some responsive.css file:
img {
max-width: 100% !important;
}
Removed that and all is fine now.
I had this issue with a site I'm working on too. We're doing some things to all <img> tags for responsiveness. This fix is working for us for the map:
img {max-width: initial !important;}
For those who might be stuck regardless of the nice solutions provided here, try setting the height and width of your container directly in the html markup instead of a stylesheet ie.
<div id="map-container" style="width: 100%; height: 300px;"></div>
happy mapping!
This may not be the case for everyone, but maybe it can help someone.
I was creating markers in my map from data attributes placed on the map element like this: data-1-lat="2" data-1-lon="3" data-text="foo". I was putting them in an array based on the order they were placed in the data attributes.
The problem is that IE and Edge (for some mad reason) invert the order of the data attributes in the HTML tag, therefore I wasn't able to correctly extract them from the data attributes.
None of the existing answers helped me because my problem was that Apollo was adding extra properties ("__typename" fields) to my MapOptions object.
In other words, the JSON looked like this:
mapOptions {"__typename":"MapOptions","center":{"__typename":"GeoCoordinates","lat":33.953056,"lng":-83.9925},"zoom":10}
Once I realized that those extra properties were problematic, this is how I solved it (using TypeScript):
function getCleanedMapOptions(mapOptionsGql: google.maps.MapOptions): google.maps.MapOptions {
const mapOptions = { ...mapOptionsGql };
const lat: number = mapOptions.center.lat as number;
const lng: number = mapOptions.center.lng as number;
const mapOptionsCleaned = {
center: new google.maps.LatLng({ lat, lng }),
zoom: mapOptions.zoom,
};
return mapOptionsCleaned;
}
export function createMap(mapOptions: google.maps.MapOptions): google.maps.Map {
const mapOptionsCleaned = getCleanedMapOptions(mapOptions);
const map = new google.maps.Map(document.getElementById('map') as HTMLElement, mapOptionsCleaned);
return map;
}
In my case (version is 3.30 when submitting this), it was because the div id MUST be "map"
<div id="map"></div>
...
document.getElementById("map")

Google Maps v3 Custom Controls - Interact with control outside of map

I am using a google maps custom control. I would like a text link outside of the map (on another place on the page) to interact with the control. Basically I want to be able to trigger a click on the custom control.
Does anyone have advice or assistance on how this can be accomplished?
This also relates to Using custom control with Google Maps KeyDragZoom - how to activate drag zoom? , decided to make a question more general.
Try directly selecting it by source:
$('img[src=http://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png]').click();
If you are trying to make KeyDragZoom turn on/off when you click on a link outside the map, you can set the onclick event on the link to run a function like this:
function toggleClickZoom() {
var myKeyDragZoom = map.getDragZoomObject();
myKeyDragZoom.buttonDiv_.onclick(document.createEvent('MouseEvent'));
}
I've managed to create custom zoom in and zoom out buttons outside the map:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 60%; width:60%; margin:20px auto; border:1px solid; padding-left:100px; }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=ADD-YOUR-API-KEY-HERE&sensor=false&region=AU">
</script>
<script type="text/javascript">
function HomeControl(controlDiv, map) {
google.maps.event.addDomListener(zoomout, 'click', function() {
var currentZoomLevel = map.getZoom();
if(currentZoomLevel != 0){
map.setZoom(currentZoomLevel - 1);}
});
google.maps.event.addDomListener(zoomin, 'click', function() {
var currentZoomLevel = map.getZoom();
if(currentZoomLevel != 21){
map.setZoom(currentZoomLevel + 1);}
});
}
var map;
/**
* The HomeControl adds a control to the map that simply
* returns the user to Chicago. This constructor takes
* the control DIV as an argument.
* #constructor
*/
function initialize() {
var mapDiv = document.getElementById('map-canvas');
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(-33.90224, 151.20215),
panControl: false,
zoomControl: false,
streetViewControl: false,
overviewMapControl: false,
mapTypeControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapDiv, mapOptions);
// Create the DIV to hold the control and
// call the HomeControl() constructor passing
// in this DIV.
var homeControlDiv = document.createElement('div');
var homeControl = new HomeControl(homeControlDiv, map);
homeControlDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_LEFT].push(homeControlDiv);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="zoomout" style="border:1px solid; width:150px; heoght:50px; cursor:pointer; margin-bottom:20px;">ZOOM ME OUT</div>
<div id="zoomin" style="border:1px solid; width:150px; heoght:50px;cursor:pointer;">ZOOM ME IN</div>
</body>
</html>
The accepted answer assumes that the zoom control is on the map. If visualEnabled is false, the dragzoom_btn image will not exist, nor will buttonDiv_.
Until external controls are officially supported, this hack seems to work:
function onZoomClick() {
var myKeyDragZoom = map.getDragZoomObject();
myKeyDragZoom.hotKeyDown_ = !myKeyDragZoom.hotKeyDown_;
}
When clicked, the zoom mode is turned on. When clicked again or the rectangle is drawn, zoom mode is automatically turned off.