Switching a Map using AJAX tabs - Google Maps API - javascript

I'm trying to setup Google Maps using the Google Maps API v3 JS code. I've got multiple tabs that when clicked open up an AJAXed page of content without reloading the original page. Each tabbed content contains a map. Below is an example of how I've got the map setup. Please note, the list element here is just an example, each tab contains many items that are in different places.
<script type="text/javascript">
var locations = new Array();
</script>
<div id="googlemap"><div>Loading..</div></div>
<ul>
<li>#1 - My Place, Euless, TX
<script type="text/javascript">
locations.push(['#1 - My Place','Euless, TX']);
</script>
</li>
<li>#2 - My Other Place, Dallas, TX
<script type="text/javascript">
locations.push(['#2 - My Other Place','Dallas, TX']);
</script>
</li>
</ul>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#googlemap div').remove();
if(locations.length>0)
{
var map = new google.maps.Map(document.getElementById('googlemap'), {
zoom: 3,
center: new google.maps.LatLng(38.065392,-97.382812),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i=0;i<locations.length;i++) {
var thelocation = locations[i];
jQuery.ajax({
dataType: 'jsonp',
url: 'http://maps.google.com/maps/geo?output=json&oe=utf8&sensor=false&key=BLAHBLAH&q='+thelocation[1],
cache: false,
success: function(data){
if(data.Status.code==200)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(data.Placemark[0].Point.coordinates[1],data.Placemark[0].Point.coordinates[0]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(thelocation[0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
});
}
}
});
</script>
I'm currently having a LOT of trouble with destroying the previous map and loading in the new one. When the tabbed content is loaded the map element appears shifted up and to the left. The Google Maps UI still appears in the correct spots, but the map content itself is moved up / left. When dragging the map it moves slightly until a certain point and at that point the visible area gets clipped back to around that same area of view. Can anyone help me that's dealt with loading new maps via AJAX?

You have to create a trigger to tie the DIV size changes to the resize event for the map.
Developers should trigger this event
on the map when the div changes size:
google.maps.event.trigger(map,
'resize') .

Related

Why am I getting gray map after loading google map for second time by click event?

On my contact page, I have 3-4 addresses. I want to show one address on google map initially, on page load. And when the user clicks on different address then marker changes and moves to that address.
Initially, on page load, I am getting google map correctly. Map shows everything perfectly fine. But when I click on different addresses to move marker, marker moves but map gets gray colored. I mean the map is not showing perfectly as it shows for the first time.
Here is the screenshot for both
Screenshot 1 (Initially, Map loads perfectly fine)
Screenshot 2 (But When I click on address to change map location it shows gray colored map)
Here is my code
$(function(){
var map;
var marker;
// Load Map function
function loadMap(lat,long, fullAddress) {
var mapCanvas = document.getElementById("store-map");
let latLong = new google.maps.LatLng(lat, long);
var mapOptions = {
center: latLong,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: latLong,
map: map,
animation: google.maps.Animation.DROP,
title: "Address"
});
var infoWindow = new google.maps.InfoWindow();
//Create and open InfoWindow.
infoWindow.setContent(fullAddress);
marker.addListener('click', function() {
infowindow.open(map, marker);
});
infoWindow.open(map, marker);
}
var defaultAddress = "448-451, Udyog Vihar, Phase - V</br>Gurugram, Haryana- 122001",
defaultLat = "28.4759576",
defaultLong = "77.0363467";
on page load load google map with default address
google.maps.event.addDomListener(window, 'load',
loadMap(defaultLat,defaultLong, defaultAddress));
// Get clickable item
var $locationItem = $('.store-location__item');
// On ckick of each address
$locationItem.on('click',function(event) {
// event.preventDefault();
/* Act on the event */
let lat = $(this).find('.lat').text();
let long = $(this).find('.lat').text();
let address = $(this).find('.store-location__address').html();
console.log(lat, long, address);
loadMap(lat,long,address);
});
});
Am I missing something? Why am I getting a gray colored map on click to change the location according to latitude and longitude after getting it from dom?
Note:
I have given latitude and longitude in HTML which has opacity 0 and
getting it on click to change the location
I also tried to create a new marker and remove the previous marker
instead of loading a new google map for performance but that is also
giving gray color issue.
I also tried to check css like 'overflow:visible' and
'overflow:hidden' but nothing happens regarding gray color issue.

Google maps not loading within js tab

I am trying to make tabs using js to have more data on the site.
Please view: http://dev.ateo.dk/officelab-konferencecenter/
The two tabs at the top ("Billeder" and "kort") are made using js.
If i go into the tap called "kort", the google maps will not load completely - however if i right-click and choose "Inspect Element (Q)" using firefox, the map suddenly loads.
Also, the map is not centered. on the specific location - the location is in the top left corner.
You may notice a blank square below the tab div. This is the exact same code as used within the js tab. If i comment out the in js tab, the square which is blank, will work perfectly. So it somehow seems that the js tab combined with the js google maps are not working. Can this be the case, and if so, how is it fixed?
Below i am showing the code which will init the google maps and the taps on the page:
if($('body.single-konferencested').length > 0)
{
tabs();
}
if($('body.single-konferencested').length > 0)
{
$(document).ready(function() {
function initialize() {
var myLatlng = new google.maps.LatLng(place_lat,place_lng);
var mapOptions = {
zoom: 9,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('gmap'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
clickable : true
});
var pinIcon = new google.maps.MarkerImage(
"http://dev.ateo.dk/wp-content/themes/ateo/img/pin_marker.png",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(24, 40)
);
marker.setIcon(pinIcon);
var content_string = '<div id="gmap_info">'+
'<div id="siteNotice">'+
'</div>'+
'<h3 id="firstHeading" class="firstHeading">'+place_title+'</h3>'+
'<div id="bodyContent">'+
'<p>'+place_address+'<br />'+place_city_zip+'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: content_string
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
});
}
This following is the html showing the DOM for the "Kort" tab:
<div class="tabContent" id="kort" style="padding: 5px 10px;">
<h2>Kort</h2>
<div id="gmap" style="width: 600px; height: 400px;"></div>
<h2>test</h2>
</div>
Best regards
Patrick
If the div in which the map is going to live is not visible on page load the map will not load correctly. You should fire a resize once the div has come into view.
google.maps.event.trigger(map, 'resize');
You should bind this to the first click of the map tab.
It looks like the map is commented out of the second tab currently. If you could uncomment it it would be easier to help you more specifically!
EDIT:
to bind the function once, try this:
var tab = jQuery('ul#tabs li')[1]
jQuery(tab).one('click', function(){
google.maps.event.trigger(map, 'resize');
});
In order for the resize to work you will need access to the map variable from your init function.
It would also be easier to select the correct tab if you drop a class on it. That would be more reliable then getting the 2nd li in the tabs ul.
EDIT 2:
try adding the click function in your initialize code. Something similar to the following
var mapOptions = {
zoom: 9,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('gmap'), mapOptions);
//add the code here, after the map variable has been instantiated
var tab = jQuery('ul#tabs li')[1]
jQuery(tab).one('click', function(){
google.maps.event.trigger(map, 'resize');
//fire a center event after the resize, this is also useful
// if bound to a window resize
map.setCenter(myLatlng)
});
//end of new code
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
clickable : true
});
It can be solved easily by re-initialize the Google Map on Tab click.
$('#kort').click(function(e) {
initialize();
resetMap(map);
});
This simple solution has found from here - How to Display Google Map Inside of a Hidden Div

google maps smartinfowindow position

I am trying to change the infowindow in Google maps to the smartinfowindow but for some reason the position of the infowindow is wrong. I never had this issue with the standard infowindow, only the smartinfowindow.
I have found that if I remove position: relative using Firefox inspector the map moves to the top left of the window and the smartinfowindows are then in the correct position.
So is there something I'm missing?
I create the markers with the following:
for (var i = 0; i < data.locations.length; i++) {
var dataPhoto = data.locations[i];
var latLng = new google.maps.LatLng(dataPhoto.latitude,dataPhoto.longitude);
latlngbounds.extend( latLng );
var marker = new google.maps.Marker({
position: latLng,
icon: 'http://www.irishcottageholidays.com/images/cottage1.png'
});
listenMarker(map,marker,InfoWindow,dataPhoto.mID)
markers.push(marker);
}
And then to create the smartinfowindow:
function listenMarker (map,marker,InfoWindow,mID){
google.maps.event.addListener(marker, 'click', function() {
load_content(map,this,InfoWindow,mID);
});
function load_content(map,marker,InfoWindow,mID){
var $j = jQuery.noConflict();
$j.ajax({
type : 'GET',
url : '/ajax/map_popup.asp',
data: {
mID : mID
},
success: function(result){
new SmartInfoWindow({position: marker.getPosition(), map: map, content: result});
}
});
}
Originally I created the infowindows using:
InfoWindow.setOptions({
disableAutoPan: true,
maxWidth: 280
});
InfoWindow.setContent(result);
InfoWindow.open(map, marker);
And this worked but now I've changed to the smartinfowindow, it loads the infowindow but not in the right position.
Thanks for all help in advance.
---- EDIT ----
I now have an issue with the smartinfowindow not closing when opening another and have been unable to achieve this so far. Everything I've found so far seem to apply to the standard infowindows and don't work on the smartinfowindow.
Thanks again for all help in advance.
I believe you should change smartinfowindow properties by editing the smartinfowindow.js file.
I've managed to get a solution through Experts Exchange.
Smartinfowindow position solution:
SmartInfoWindow creates a div to contain the content of the infowindow and appends it to the body. It's position is set to absolute relative to the body. It assumes your map is in the top left corner of the document.
The simple solution is to absolute position the SmartInfoWindow relative to the map canvas instead of the body. To do this you must edit the smartinfowindow.js file on line 178.
Instead of:
document.body.appendChild(div);
Replace with:
var mapDiv = document.getElementById("map");
mapDiv.appendChild(div);
With "map" as the id of the div that holds the map.
Remove smartinfowindow when opening a new one:
function listenMarker (map,marker,InfoWindow,mID){
google.maps.event.addListener(marker, 'click', function() {
if ($('#map > div').length > 1) { $('#map >div:last-child').remove(); }
load_content(map,this,InfoWindow,mID);
});
}
Where:
if ($('#map > div').length > 1) { $('#map >div:last-child').remove(); }
was added to my code
It assumes you have jquery on the page already and no other google map add-ons are creating divs inside the map div.
All credit to tommyBoy on Experts Exchange for both solutions.

Javascript google maps

I have multiple locations of my company's regional offices and have to show each location whenever user clicks at a locations like:
location1
location2
location3
When user clicks at location 1 it will show location 1 on the map. I also have those locations in my maps. I have never worked with Google maps before, so I just need some idea to get started.
When your user clicks a link, run a piece a javascript that calls setCenter(latlng:LatLng) on the map to center the map to a certain location.
If you really don't know where to begin, then start by reading the Google Maps API documentation. It's easy to read, and it contains lots of working examples.
You can do something like this: (I'm sure it could be optimized with a for loop, its early/late right now.
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() { //Initalize JS after onload
var map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
var randomPoint1 = new google.maps.LatLng(44.6479, -63.5744); //First Location
var marker1 = new google.maps.Marker({ //Set up marker
position: randomPoint1,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid1'), 'click', //Set up DOM listener 1
function(){
map.setZoom(13);
map.setCenter(marker1.getPosition());
});
var randomPoint2 = new google.maps.LatLng(45.5081, -73.5550); //Second Location
var marker2 = new google.maps.Marker({
position: randomPoint2,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid2'), 'click',//Set up DOM listener 2
function(){
map.setZoom(13);
map.setCenter(marker2.getPosition());
});
var randomPoint3 = new google.maps.LatLng(43.6481, -79.4042); //Third Location
var marker3 = new google.maps.Marker({
position: randomPoint3,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid3'), 'click', //Set up DOM listener 3
function(){
map.setZoom(13);
map.setCenter(marker3.getPosition());
});
map.setCenter(marker2.getPosition());
map.setZoom(5);
}
</script>
</head>
<body onload="initialize()"> <!--Initalize JS after onload--->
Halifax
Montreal
Toronto
<div id="map_canvas" style="height:100%; width:100%"></div>
</body>
</html>
And after I write this I realize the post was from last August. Oh well, may help someone at some point.

Retrieve position of a google maps v3 marker to Qt in a desktop app with QtWebKit

I'm building a Qt app with Python where you can point and click at a (google) map and get the coordinates of the location. The map is shown through a QWebView loading a simple HTML page and the user can create markers by clicking. Screenshot of the widget after clicking on the map.
However, I'm having trouble to retrieve the just-clicked location coordinates back to Qt (so that I can use them as variables -- and, for example, show them in the QLineEdits on the topleft corner above, as current location of the marker).
This is the relevant part of the HTML file:
<script type="text/javascript">
var map;
function initialize() {
var local = new google.maps.LatLng(-23.4,-40.3);
var myOptions = {
zoom: 5,
center: local,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'rightclick', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var clickedLocation = new google.maps.LatLng(location);
var marker = new google.maps.Marker({
position: location,
map: map
});
map.setCenter(location);
}
function dummyTxt() {
return 'This works.';
}
</script>
I've been trying with evaluateJavaScript, but was not able to retrieve the coordinates. I tried to created a function to access the position with marker.getPosition(), but with no luck. The dummy below works though..
newplace = QWebView.page().mainFrame().evaluateJavaScript(QString('dummyTxt()'))
>>> print newplace.toString()
This works.
Any suggestions on how to get the coordinates back to Qt?
Edit:
Here is the code that worked for me:
def update_geo(self):
# Capture coordinates of the last marker on the map.
mark = self.map.page().mainFrame().evaluateJavaScript('document.getElementById("markerlocation").value').toString()
# Convert string to list of floats, stripping parentheses.
marker = str(mark).strip('()').split(', ')
decimals = [float(c) for c in marker]
Full source in https://github.com/nelas/veliger/blob/master/veliger.py#L2374
I found a work around to make it work but I'm not pretty sure that it will be the right approach. Anyway, this is what I did:
Create a hidden input in the body section of your html document to save the position data of the marker:
<body>
(...)
<input id="locationData" type="hidden">
(...)
</body>
In the javascript code, save the position of the marker in the hidden input every time it's created:
function placeMarker(location) {
(...)
document.getElementById("locationData").value = marker.position;
(...)
}
In your Qt code, read the value of the hidden input with the instruction:
webView->page()->mainFrame()->findFirstElement("#locationData").evaluateJavaScript("this.value").toString();
I hope it helps!
Source: http://opendocs.net/qt/4.6/webkit-formextractor.html

Categories

Resources