I'm building a mobile map using the Google Map API V3. The is a little different than a standard map in that I have categories of markers than you can turn on/off. Everything works great, but I can't seem to get geolocation working. I've tried every combination and code snippet I can find and at most I can get it to register the location request, but it will not display a marker there no matter what I do. I'm sure I'm doing something very simple wrong, but I'm very new to Javascript so the answer is evading me.
Here is a shortened version of my current code (contains an example of everything, but cuts out a lot of the repetitive variables). This example doesn't include the geolocation functions since I've tried so many in different ways I'm not sure which one I would even put on here. The toggleMarkers() function is what I'm using to turn on/off the markers and I'm guessing that's where the problem is for the geolocation marker being displayed. If you could show me how to implement geolocation within this code I would greatly appreciate it!
var markers = [];
function initialize() {
//Setting Map
var mapOptions = {
zoom: 18,
center: new google.maps.LatLng(45.73158,-122.636277),
mapTypeId: 'satellite'
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(0);
//Marker Categories
var markerBuildings = {
category: 'buildings',
}
var markerParking = {
category: 'parking',
}
// Icons
var iconBuilding = new google.maps.MarkerImage('images/building.png',
new google.maps.Size(32, 37),
new google.maps.Point(0,0),
new google.maps.Point(16,32));
var iconAmphitheater = new google.maps.MarkerImage('images/amphitheater.png',
new google.maps.Size(32, 37),
new google.maps.Point(0,0),
new google.maps.Point(16,32));
//Coordinates
//Buildings
var vmcb = new google.maps.Marker({
position: new google.maps.LatLng(45.730513,-122.638106),
map: map,
url: 'http://www.google.com/',
icon: iconBuilding,
data: markerBuildings
});
markers.push(vmcb);
var vadm = new google.maps.Marker({
position: new google.maps.LatLng(45.730899,-122.637742),
map: map,
url: 'http://www.google.com/',
icon: iconBuilding,
data: markerBuildings
});
markers.push(vadm);
}
function toggleMarkers(attr,val) {
if (markers){
for (i in markers) {
if(markers[i].data[attr] == val){
var visibility = (markers[i].getVisible() == true) ? false : true;
markers[i].setVisible(visibility);
}
}
}
}
If you could show me how to implement geolocation within this code I would greatly appreciate it!
call getGeoLocation() (below) after you create the map object
function getGeoLocation() {
// http://stackoverflow.com/questions/3397585/navigator-geolocation-getcurrentposition-sometimes-works-sometimes-doesnt
var options = null;
if (navigator.geolocation) {
if (!browserChrome) {
// By using the 'maximumAge' option, the position
// object is guaranteed to be at most 15 seconds old.
// FF and Safari seem to like these options; Chrome does not
options={enableHighAccuracy: false, maximumAge: 15000, timeout: 30000};
}
else {
// Request a position. We only accept cached positions, no matter what
// their age is. If the user agent does not have a cached position at
// all, it will immediately invoke the error callback.
// http://dev.w3.org/geo/api/spec-source.html
// Chrome will not allow this submitted via the file:// protocol
options={maximumAge:Infinity, timeout:0};
}
navigator.geolocation.getCurrentPosition(function(position) {
centerIsSet = true
canGeolocate = true;
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(pos);
},
getGeoLocationErrorCallback(true),
options);
}
else {
// browser doesn't support geolocation
getGeoLocationErrorCallback(false);
}
}
Related
Using v.3 of the Google geocoder api with a Java back end, Velocity front end and an Oracle db.
Our current spec specifies that when a user selects a marker (lat/lng) that their zoom should be saved as well for future sessions. I can't for the life of me figure out how to do this. I have seen some information about bounds which I think I may be able to use in a hackey way, but I don't want to define the bounds of the map, I just want to save the zoom (like the lat/lng) and be able to pass it to the back end.
map.js
var geocoder;
var map;
var siteLocation;
var marker;
function initMap() {
var lat = parseFloat($("#newLat").val());
var lng = parseFloat($("#newLng").val());
geocoder = new google.maps.Geocoder();
siteLocation = { lat: lat, lng: lng };
map = new google.maps.Map(document.getElementById('map'),
{
center: siteLocation,
zoom: 19,
}
);
//set crosshair
console.log('setting waypoint marker');
crosshair = new google.maps.Marker(
{
position: siteLocation,
map: map,
draggable: false,
shape: { coords: [0, 0, 0, 0], type: 'rect' },
icon: "https://www.daftlogic.com/images/cross-hairs.gif"
}
);
crosshair.bindTo('position', map, 'center');
geocodeLatLng();
}
//use new selection to
function geocodeLatLng() {
var lat = crosshair.getPosition().lat();
var lng = crosshair.getPosition().lng();
var newLocation = crosshair.getPosition();
geocoder.geocode({ location : crosshair.position}, function(results, status) {
if (status == 'OK') {
results[0].geometry.location.lat();
results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
//get new user selected map options, [drop marker] (optional)
$("#addGeolocation").on("click", function (evt) {
geocodeLatLng();
evt.preventDefault();
var newZoom = map.getZoom();
var newLat = crosshair.getPosition().lat();
var newLng = crosshair.getPosition().lng();
$("#newLat").val(newLat);
$("#newLng").val(newLng);
newLocation = new google.maps.LatLng(newLat, newLng);
map.setCenter(newLocation);
map.setZoom(newZoom);
//make sure no marker exists
if ( marker !== undefined) {
marker.setPosition(newLocation);
} else {
marker = new google.maps.Marker({
position: newLocation,
map: map,
draggable: true
});
}
});
Velocity Macro
#macro(map $ADDRESS)
<script defer
src="https://maps.googleapis.com/maps/api/js?key=${GOOGLE_API_KEY}&callback=initMap">
</script>
<div id="map"></div>
<span class="innerBlock smallBlock" id="map" ></span>
<button type="button" onclick="geocodeLatLng()" id="addGeolocation"> $BTN_ADD_GEOLOCATION</button>
#inp_hidden("newLat" "$context.getSite().getLatitude()")
#inp_hidden("newLng" "$context.getSite().getLongitude()")
#inp_hidden("newZoom")
#end
I am completely stumped. Any ideas? Most of the solutions I have seen involve cookies but we cannot use those. Any advice would be appreciated. Thanks!
I think I understand what you mean but correct me if I'm wrong.
You could save the zoom level in a variable.
var zoom = 16;
and then save this in the local storage
localStorage.setItem("zoomLevel", zoom);
then use getItem method to retrieve it
var savedZoom = localStorage.getItem("zoomLevel");
So if you were planning to have the zoom levels in a select box or something, you can save the users choice into the local storage and then retrieve it when they return by setting to zoom to 'savedZoom' for example.
I'm not completely sure if this is what you were after but hopefully it helps. I've tried not to go into too much detail just incase it isn't.
I have a script that:
pulls results from a database in the form of an XML file
parses those results
creates a marker for each result and places it on a map (a single map for all markers)
at the same times, builds a clickable HTML list (sidebar) containing all those results.
When the user clicks on a place name in the sidebar, the info window from the corresponding marker on the map is automatically displayed. Of course the user can also click directly on a marker on the map, and the same info window is also displayed.
This code has been working fine for several years, but last week I noticed that its behavior was now bugged. When viewing some given results, the first click (either on the map or in the sidebar) works fine (the info window opens and displays the correct information), but the following clicks all show the same information from the first click, all in their respective info window. (To be clear: the information shown is the one from the very first click, not from the previous click.)
I've been trying to debug that for hours but I don't understand why it doesn't work anymore. As you can see in my code below, I tried adding a console.log in the google.maps.event.addListener function, to see what data is being worked with when the marker is clicked, but even there, I don't see anything wrong.
Here is my code (simplified to be more readable):
var side_bar_html = '\n';
var gmarkers = []; // array for created markers
var infoWindow;
var center_lat = <?php echo $position_lat; ?>;
var center_lng = <?php echo $position_lng; ?>;
function createMarker(point, name, html, place_id, map) {
var marker, markerOptions;
markerOptions = {
map: map,
position: point,
dataId: place_id,
icon : 'theme/marker.png',
shadow: 'theme/marker_shadow.png'
};
marker = new google.maps.Marker(markerOptions);
infoWindow = new google.maps.InfoWindow({content: html});
google.maps.event.addListener(marker, 'click', function() {
console.log(this, marker, html);
infoWindow.content = html;
infoWindow.open(map, this);
});
gmarkers.push(marker);
side_bar_html += '\n<li>' + name + '</li>';
return marker;
}
function showPlace(i) {
google.maps.event.trigger(gmarkers[i], 'click');
}
function loadEarth(opt, zoom) {
var map, point, mapCenter, mapOptions;
if (zoom === null) {zoom = 7;}
mapCenter = new google.maps.LatLng(center_lat, center_lng);
mapOptions = {
zoom: zoom,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
point = new google.maps.LatLng(parseFloat(center_lat), parseFloat(center_lng));
if (opt != 0) {
map.setMap(new google.maps.Marker(point));
}
}
// receiving results via XML
function go() {
var map, bounds;
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
bounds = new google.maps.LatLngBounds();
$.ajax({
url : 'url/to/data.xml',
type : 'GET',
dataType : 'xml',
success : function(xml) {
var markers, lat, lng, place_id, point, label, html, marker;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// extract data for each marker
lat = parseFloat(markers[i].getAttribute("lat"));
lng = parseFloat(markers[i].getAttribute("lng"));
place_id = parseFloat(markers[i].getAttribute("place_id"));
point = new google.maps.LatLng(lat,lng);
label = $(markers[i]).find('label').eq(0).text();
html = $(markers[i]).find('infowindow').eq(0).text();
// marker creation
marker = createMarker(point, label, html, place_id, map);
// extend visible zone to newly added marker
bounds.extend(point);
}
map.setCenter(new google.maps.LatLng(center_lat, center_lng), 7);
bounds.extend(point);
if (markers.length>0) {
document.getElementById("side_results").innerHTML = side_bar_html;
map.fitBounds(bounds);
map.setCenter(bounds.getCenter());
} else {
loadEarth();
}
} // end AJAX success
}); // end AJAX
} // end go()
if ($('#places_page').is('.empty')) {
loadEarth(0,8);
} else go();
Any help would be greatly appreciated.
Edit:
As requested, here's a sample of the XML received. In this case, the PHP variables at the start of the script would receive the following values:
$position_lat: 46.9479222
$position_lng: 7.4446085
<?xml version="1.0" encoding="UTF-8"?><markers>
<marker place_id="955" lat="46.950218" lng="7.442429">
<label><![CDATA[<em>Place 955</em><strong>3011 Bern</strong>]]></label>
<infowindow>
<![CDATA[<p><em>Place 955</em><br />Speichergasse 35<br />3011 <ins>Bern</ins></p>]]>
</infowindow>
</marker>
<marker place_id="985" lat="46.942032" lng="7.389993">
<label><![CDATA[<em>Place 985</em><strong>3018 Bern</strong>]]></label>
<infowindow>
<![CDATA[<p><em>Place 985</em><br />BrĂ¼nnenstrasse 106A<br />3018 <ins>Bern</ins></p>]]>
</infowindow>
</marker>
</markers>
The Google Maps API is included via this line:
<script src="http://maps.google.com/maps/api/js?v=3&sensor=true&language=fr&key=..."></script>
Edit 2:
Changing the API call to force it to use version 3.18 does fix the problem:
<script src="http://maps.google.com/maps/api/js?v=3.18&sensor=true&language=fr&key=..."></script>
Obviously this is a temporary fix, since v. 3.18 won't always be available. Now I need to understand what change in the 3.19 version made this bug appear. Any suggestion is still appreciated. :)
This undocumented usage:
infoWindow.content = html;
May be the issue. Should be:
infoWindow.setContent(html);
The .content property went away or is no longer supported issue
I'm clueless as to why this won't run on my mobile browser but it will run on my PC browser, chrome to be exact.
Could any of you provide feedback.
Link to the server I'm testing this on:
54.172.35.180/chat/chatlist.php
<script type="text/javascript">
function success(position) {
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 15,
center: latlng,
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"You are here! (at least within a "+position.coords.accuracy+" meter radius)"
});
}
google.maps.event.addDomListener(window, 'load', navigator.geolocation.getCurrentPosition(success));
</script>
I originally just copied and pasted the code from the API site and it worked fine but as soon as I started pulling GPS data it stopped working on my mobile device's browser. Any help would be appreciated.
navigator.geolocation.getCurrentPosition doesn't return a position. So you can't use that result as a parameter of addDomListener(window, ...
What it does, is send a request. When that request is ready, a callback is triggerd. In that callback you can trigger your function success() (I named it initialize).
Just to show what's going on.
You can still choose if this is a good way to proceed.
Feel free to rename, extend, ...
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
function initialize(position, accuracy) {
var latlng = position || new google.maps.LatLng(50.45, 4.45); // set your own default location. This gets called if the parameters are left blank.
var myOptions = {
zoom: 15,
center: latlng
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
if (position) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "You are here! (at least within a " + accuracy + " meter radius)"
});
}
else {
// position of the user not found
}
}
function locationFound(position) {
initialize(
new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
position.coords.accuracy
);
}
function locationNotFound() {
initialize(null, null);
}
function page_loaded() {
// the page is loaded, we can send a request to search for the location of the user
navigator.geolocation.getCurrentPosition(locationFound, locationNotFound);
}
google.maps.event.addDomListener(window, 'load', page_loaded);
</script>
<style>
#map-canvas {
width: 500px;
height: 400px;
}
</style>
<div id="map-canvas"></div>
Probably it's a better idea to first load a map and set a default location.
When the location is found, you change the center and set the marker.
Notice now: if the location is not found, it takes quite a long time before locationNotFound is called
I am working on a website that have multiple companies and employees, each company should register by entering its username,password and location on Google maps.
The location is going to appear to employees who are using an android application (Which is connected to the same website's database).
I want to know how to allow the company to specify their exact address either by typing the decimal points of the location or by using the pin to specify it on Google map or by allowing me to detect their location.
I read this: https://developers.google.com/maps/documentation/javascript/tutorial
but I do not know if it is what I need in my case.
Note that it is the first time for me to deal with maps so I am not deep into it.
I hope i understand you correctly.
One option could be something like this:
Get the user device' geolocation and put that position on a map with a draggable marker.
If the position is not correct, marker can be dragged and you will get the new coords - if the marker location has been changed.
Here is the code (with jquery):
var map;
var marker;
function initialize() {
var mapOptions = {
zoom: 11
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
position: pos,
map: map,
title: 'Here you are',
draggable: true
});
$('#user-info').append('Location found using HTML5<br/>');
map.setCenter(pos);
google.maps.event.addListener(marker, 'dragend', function(a) {
$('#user-info').append(a.latLng.lat().toFixed(4) + ', ' + a.latLng.lng().toFixed(4) +'<br/>' );
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
$('#user-info').append('Error: The Geolocation service failed.');
} else {
$('#user-info').append('Error: Your browser doesn\'t support geolocation.');
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
};
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
http://jsfiddle.net/iambnz/xdoc1nxm/
I hope this will help you.
In case you will need to get the exact address, you have to add geocoding functionality.
This certainly touches on previous questions regarding map display during initialization. Yet the issue here is with map display being set to none after map should have already initialized. The last line of my widow.onload sets the map to display: none; The map initialization should have already completed by that time, but the fact remains, the final call is causing the problem.
window.onload(); function...
window.onload = function(){
changeTheme(me); // do it now so current_theme is avaible to switchTabs();
switchTabs("tab3"); // sets map div visible
initMaps(); // map initialization. code included.
loadFavoritePlaces(); // asynch $getJSON call, adds markers. No matter the condition of map, markers appear in their proper locations.
closePopup("images");
closePopup("location"); // sets maps.mini_map display: none; Problems if we loadUserTable() later. Otherwise OK. Odd!
closePopup("tweet");
centerDiv();
document.title = '#'+me.screen_name+' - PithyTwits.com';
users[me.id_str] = me;
getPage(); // asynch $.getJSON loads tweets. Not an issue.
// Append a scroll event handler to tweet_div
$("#tweet_div").scroll(function() {
var pos = $(this)[0].scrollHeight - $(this).scrollTop();
if(pos != prev_scroll){ // hack to prevent scroll function from firing twice
prev_scroll = pos;
if (pos == $(this).outerHeight()) {
$("#throbber").fadeIn();
getPage();
}
}
});
loadUserTable(me.id_str);
/* loadUserTable(); calls switchTabs("tab1"); which sets map div display: none;
if I comment this out the map initialization completes properly, but my 'tab1'
doesn't get populated properly. And page doesn't start on 'tab1', which is required. */
// end window.onload()
}
initMaps(); function...
function initMaps() {
// markers list
maps.markers = new Object;
// visibility status'
maps.markerStatus = new Object;
maps.markerStatus['query'] = true;
maps.markerStatus['tweet'] = true;
maps.markerStatus['favorite'] = true;
// define marker images
maps.reticleImage = new google.maps.MarkerImage('images/reticle.png',
new google.maps.Size(63, 63),
new google.maps.Point(0,0),
...
Declarations removed to streamline post.
...
new google.maps.Point(0,0),
new google.maps.Point(1, 13));
maps.markerShape = {
type: "poly",
coords: [9,22,16,11,16,5,11,1,6,1,2,5,2,11,9,22]
}
// setup map options
var latlng = new google.maps.LatLng(39.520427, -94.770621);
var latlng2 = new google.maps.LatLng(46.1912, -122.1944);
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var myOptions2 = {
zoom: 13,
center: latlng2,
disableDefaultUI: true,
draggable: false,
keyboardShortcuts: false,
mapTypeControl: false,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.HYBRID
};
// initialize maps
maps.main_map = new google.maps.Map(document.getElementById("map_div"), myOptions);
maps.mini_map = new google.maps.Map(document.getElementById("mini_map"), myOptions2);
// default map center markers
maps.mini_map_marker = new google.maps.Marker({
position: latlng2,
map: maps.mini_map,
icon: maps.favoriteMarker,
shadow: maps.markerShadow,
});
maps.reticleMarker = new google.maps.Marker({
position: latlng,
map: maps.main_map,
shape: reticleShape,
icon: maps.reticleImage,
});
// event handlers
google.maps.event.addListener(maps.main_map, 'zoom_changed', mapZoomed);
google.maps.event.addListener(maps.main_map, 'bounds_changed',
function(){maps.reticleMarker.setPosition(maps.main_map.getCenter());});
//idle event listener provided by #Guan in the marked answer.
google.maps.event.addListenerOnce(maps.main_map, 'idle', function() {
var div = document.getElementById("tab3_content");
div.style.display = "none";
div.style.position = "relative";
div.style.left = "0px";
});
// initialize controls
var controls = document.getElementById("visibility_controls");
maps.main_map.controls[google.maps.ControlPosition.TOP_CENTER].push(controls);
controls.style.display = "inline";
var controls = document.getElementById("control_controls");
maps.main_map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(controls);
controls.style.display = "inline";
var controls = document.getElementById("query_controls");
maps.main_map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(controls);
controls.style.display = "inline";
}
If I call loadUserTable(); at the end of window.onload(); I get this... (munged)
If I don't call loadUserTable(); at the end of window.onload(); I get this... (correct)
Since the problem stems from the maps display being set to none after the maps should have initialized, it would lead one to believe that the map initialization is actually happening non-syncronously. So how do I know when it is finished, and it is safe to hide the maps div? And also there is the question of why the mini_map seems to be dependent on visibility of the main_map, rather than its own visibility? I get the same results in both Chrome and Firefox, on Linux.
Any help is help :)
Skip
UPDATE: I changed the final call to setTimeout("loadUserTable();", 1000); and 1 second is enough of a pause to let things work, but isn't what I want! Since #Jobsz verifies this is known issue, I'm going to resort to off screen initialization, and move the map into position either when needed for display, or hide it and put it in position after a short timeout.
SOLUTION: Provided by #Guan (Checked answer)
I did not want the map visible during initialization. But wanted it initialized and ready when the user chose that tab.
The map div is initially set thus...
id="tab3_content" style="display: block;position: absolute; left: -1000px;"
That makes it visible, but offscreen to the left.
And then set a listener for the idle event in the map initialization...
google.maps.event.addListenerOnce(maps.main_map, 'idle', function() {
var div = document.getElementById("tab3_content");
div.style.display = "none";
div.style.position = "relative";
div.style.left = "0px";
});
That event fires once when the map is idle(ready). It hides the div and moves it into position on screen.
The loadUserTable() function is called in the normal program flow, and life is good. :)
Could you try calling
//map hold's a reference to your current map
google.maps.event.trigger(map, 'resize');
After the map/div containing it becomes visible?
google.maps.event.addListenerOnce(map, 'idle', function() {
$('#addstop').css({
display: 'none',
left: '0',
top: '0'
});
});
This event happens only once after the map is fully loaded and 'idle'
Yup -- I had this same problem.
What I did was trigger the initialization after the event button that displays the hidden map is clicked.
So I have a hidden div, when it's clicked to shown, i display it and then initalize it. Is this doable for what you're trying to achieve? I'm assuming you want performance in that you'd prefer the click to instantly show a populated map -- however it isn't too slow to populate the small area you're tying to if you do it on the click event.
Just this may help you.
I just have an application that uses tabs mixed with gmap divs.
I was fix same problems. Console just show corruption image message. Your ideas help a lot!
I just use this
$("#tab-3").click(function(){
$(".tab-3").removeClass("ui-screen-hidden");
$(".tab-1").addClass("ui-screen-hidden");
$(".tab-2").addClass("ui-screen-hidden");
initializedonationlocation();
})
function initializedonationlocationdr() {
var directionsDisplay = new google.maps.DirectionsRenderer();
geocoder2 = new google.maps.Geocoder();
infowindow2 = new google.maps.InfoWindow();
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(38.7,-121.59),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map2 = new google.maps.Map(document.getElementById('my_map_donation_donationreceipt'),
myOptions);
google.maps.event.addListener(map2, 'click', function(e) {
geocoder.geocode(
{'latLng': e.latLng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
if (marker2) {
marker2.setPosition(e.latLng);
} else {
marker2 = new google.maps.Marker({
position: e.latLng,
map: map2});
}
infowindow2.setContent(results[0].formatted_address);
var postCode = extractFromAdress(results[0].address_components, "postal_code");
var street = extractFromAdress(results[0].address_components, "route");
var town = extractFromAdress(results[0].address_components, "locality");
var country = extractFromAdress(results[0].address_components, "country");
var state = extractFromAdress(results[0].address_components, "administrative_area_level_1");
$("#city_donationdr").val(town);
$("#state_donationdr").val(state);
$("#zip_donationdr").val(postCode);
$("#address_donationdr").val(street);
infowindow2.open(map2, marker2);
// Changing window
var prevSelection3 = $("#tabmap").val();
var newSelection3 = $("#navbar2 ul li").children("a").attr("data-tab-class");
$("."+prevSelection3).addClass("ui-screen-hidden");
$("."+newSelection3).removeClass("ui-screen-hidden");
prevSelection3 = newSelection3;
$("#tabmap").val(prevSelection3);
document.getElementById('geocoding').innerHTML = "";
$("#coords_donationdr").val(e.latLng);
$("#address_donationdr").focus();
GetCurbSideCoordsDR(directionsDisplay,map2);
} else {
document.getElementById('geocoding').innerHTML =
'No results found';
}
} else {
document.getElementById('geocoding').innerHTML =
'Geocoder failed due to: ' + status;
}
});
});
}
I only call initialization only when tab that contain gmap is showed. NOT before. Many forums show gmap initialization at pages loading. In conbination with tabs, just only call initialization after tab appears.