I'm trying to put together a Rails app that has a bit of ajax. The problem is that the ajax parts, which call a page to load, aren't showing the Google maps. Everything else is there on the page, but not the Google maps.
When I click refresh, the page with the maps loads as it should do, but from then on, when I click on a link, the maps are missing - even though everything else in the page is there.
The script that contains my map does not even load. I mean when I put console.log("hello") between by script tags, 'hello' doesn't appear in my console. It does appear when I refresh the page, but not when using the ajax links.
Does anyone know why, or have some code to help me out? I tried:
$(document).ready(function(){
google.maps.event.trigger(map, 'resize');
});
at the top of my show.html.erb, but couldn't get it working. If it's any help, the code for my map script is:
<div id="map_canvas">
<script type="text/javascript">
console.log("hello")
var map;
var markers = [];
function initialize_google_maps() {
var currentlatlng = new google.maps.LatLng(<%= #user.lat %>, <%= #user.lng %>);
var zoom = <%= #kms_range %> > 9 ? 9 : 10;
var myOptions = {
zoom: zoom,
center: currentlatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP, // ROADMAP, SATELLITE, HYBRID
streetViewControl: false
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({map: map, position: currentlatlng, icon:{oppacity:0}});
map.setCenter(currentlatlng);
map.setZoom(zoom);
var circle = new google.maps.Circle({
map: map,
fillOpacity: 0,
strokeWeight: 2,
strokeOpacity: 0.7,
radius: <%= #kms_range %>*1000,
});
circle.bindTo('center', marker, 'position');
}
function show_markers() {
if (markers)
for(i in markers) {
markers[i].setMap(map);
}
}
function add_marker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
// markers.setVisible(false);
}
function initialize_markers() {
<% (#reviews || []).each do |r| %>
<% next unless r.lat && r.lng %>
position = new google.maps.LatLng(<%= r.lat %>, <%= r.lng %>);
add_marker(position);
<% end %>
}
$(function() {
initialize_google_maps();
initialize_markers();
show_markers();
});
</script>
</div>
My Ajax Code is:
$(document).on("ready", function(){
var ajax_loaded = (function(response) {
$(".page-content")
.html($(response).filter(".page-content"));
$(".page-content .ajax").on("click",ajax_load);
});
var form_submit = (function(e) {
e.preventDefault();
var url = $(this).attr("action");
var method = $(this).attr("method");
var data = {}
$(this).find("input, textarea, select").each(function(i){
var name = $(this).attr("name");
var value = $(this).val();
data[name] =value;
});
$.ajax({
"url": url,
"type": method,
"data": data,
"success": ajax_loaded,
"error": function () {alert("bad");}
});
});
var history = [];
var current_url_method;
var ajax_load = (function(e) {
e.preventDefault();
history.push(this);
var url =$(this).attr("href");
var method = $(this).attr("data-method");
if (current_url_method != url + method) {
current_url_method = url + method;
$.ajax({
"url": url,
"type": method,
"success": ajax_loaded,
});
}
});
$("#menu a").on("click",ajax_load);
$("#menu a.main").trigger("click");
$(".search-box form").on("submit", form_submit);
});
Did you solve the problem?
I have the same problem(map not show by ajax load page) before
but my problem is because I not give correct lat and lng
maybe you would make sure value are right on your code
var myOptions = {
zoom: zoom,<br>
center: currentlatlng,<br>
mapTypeId: google.maps.MapTypeId.ROADMAP, // ROADMAP, SATELLITE, HYBRID<br>
streetViewControl: false<br>
};
and
set up your div width and height like <div id="map_canvas" style="width:800px"
height:450px"></div>
I remember google map need width and height
Related
I'm stuck on this problem, no matter what I have tried, I cannot add a url to the google maps marker.
Can anyone with more experience than me please help with this problem.
Currently, if I click the marker, I'm taking back to the home page, what I want is to go to this url '/Hotel/Full-Details?=#item.DisplayHotelName&propId=#item.HotelId'which is in the foreach loop.
I have looked at
google map api: open url by clicking at marker
Google Map marker url
and other but i'm stuck
My code is:
<script type="text/javascript">
$(function() {
var map;
var markersArray = [];
var image = 'img/';
var bounds = new window.google.maps.LatLngBounds();
var loc;
//var pageUrl;
var mapOptions = { mapTypeId: window.google.maps.MapTypeId.ROADMAP };
map = new window.google.maps.Map(document.getElementById("dvMap"), mapOptions);
#foreach (var item in Model.DisplayHotelPaging)
{
<text> loc = new google.maps.LatLng(#item.Latitude, #item.Longitude);
bounds.extend(loc);
addMarker(loc, '#item.DisplayHotelName #item.Address1 #item.PostalCode', "active",'/Hotel/Full-Details?=#item.DisplayHotelName&propId=#item.HotelId')
</text>
}
map.fitBounds(bounds);
map.panToBounds(bounds);
//for (var i = 0; i < window.addMarker.length; i++) {
function addMarker(location, name, active) {
//var page = loc[i];
var marker = new google.maps.Marker({
position: location,
map: map,
title: name,
status: active,
icon: '/Images/property1.png',
url: '/'//page[3]
});
// }
window.google.maps.event.addListener(marker, 'click', function() {
window.location.href = marker.url;
});
}
});
</script>
Thanks for any help
I believe you need to add the URL to your addMarker function like so:
function addMarker(location, name, active, markerUrl) {
//var page = loc[i];
var marker = new google.maps.Marker({
position: location,
map: map,
title: name,
status: active,
icon: '/Images/property1.png',
url: markerUrl
});
// }
window.google.maps.event.addListener(marker, 'click', function() {
window.location.href = marker.url;
});
}
Currently you hard-coded '/' as your URL which would take you to your home page.
I have a mapping page which retrieves a json response and creates the relevant array of points to load a heatmap.
All of this is in the required initialize query which is loaded is called in a jquery document.ready.
Here is the strange thing though, all the external data is returning fine and being populated fine, the points array is fine also.
However when I call the setMap(map) method on the heatmap it does not display. But weirdly if I use an on page link to toggle it on or off it will display. Any ideas?? No errors at all in firebug.
var map;
var markers = [];
var markerLatLngArray = [];
function toggleHeatmap() {
heatmap.setMap(heatmap.getMap() ? null : map);
}
function initialize() {
var map_options = {
center: new google.maps.LatLng(53.4902, -7.96),
zoom: 7,
mapTypeId: google.maps.MapTypeId.TERRAIN,
draggableCursor: 'crosshair',
mapTypeControl: true,
scaleControl: true,
streetViewControl: false,
overviewMapControl: false,
overviewMapControlOptions: {
opened: false
}
};
map = new google.maps.Map(document.getElementById('map_canvas'), map_options);
google.maps.event.addListenerOnce(map, 'idle', function(){
document.getElementById('ajax_loading_icon').style.display = "none";
document.getElementById('map_canvas').style.visibility = "visible";
});
jQuery.get("<?php echo $data_url; ?>", {}, function(data) {
jQuery(data).find("marker").each(function() {
var marker = jQuery(this);
var latlng = new google.maps.LatLng(parseFloat(marker.attr("lat")),
parseFloat(marker.attr("long")));
markerLatLngArray.push(latlng);
});
});
pointArray = new google.maps.MVCArray(markerLatLngArray);
heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray
});
heatmap.setMap(map);
}
It is a timing problem. The map is not initialized until after heatmap.setMap is called.
I was messing about with some code but I am struggling a little bit to achieve what I want. In the example here I have a map which displays when there are coordinates in my fields:
http://jsfiddle.net/spadez/xJhmk/9/
// Generic Map Display
function mapDisplay() {
var latval = $('#lat').val(),
lngval = $('#lng').val();
if ($.trim(latval) != '' && $.trim(lngval) != '') {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(latval, lngval),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false,
draggable: false
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
$('#map_canvas').removeClass('hidden');
} else {
$('#map_canvas').addClass('hidden');
}
}
What I want to do is have this execute once per page, so that if there are values in the fields when the page loads then the map displays, but if the values get deleted after the page load or changes, the map will not change, since it read the variables at the start of ther page load only.
Can someone show me on my jsfiddle how that might be displayed please?
You are not calling the function mapDisplay();, on document ready call mapDisplay
jQuery(function($){
mapDisplay();
})
Demo: Fiddle
window.onload = function(){
mapDisplay();
}
This runs your code on the onload event
Use:
$(function()
{
mapDisplay();
}
// Generic Map Display
function mapDisplay() {
var latval = $('#lat').val(),
lngval = $('#lng').val();
if ($.trim(latval) != '' && $.trim(lngval) != '') {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(latval, lngval),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false,
draggable: false
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
$('#map_canvas').removeClass('hidden');
} else {
$('#map_canvas').addClass('hidden');
}
}
You declare a function, and after page is loaded (the $(function() {} ), it is executed.
We're building a google map app in rails that initially loads some makers using a javascript json marker generating function (using the rails .to_json method on the data object).
Then we have a listener on the zoom action that hoovers the new json file directly and feeds it into the same marker function above.
On initial load the markers turn up fine, but on zoom no new ones seem to be showing up. Checking in the rails logs, the json file is being called, so the problem is either to do with how that json data is processed, or how the markers are delivered.
Can any of you see what the problem is?
var map;
function initialize() {
var myOptions = {
zoom: <%= #zoom %>,
center: new google.maps.LatLng(<%= #centre %>),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
stream_json = (<%= raw(#stream.to_json) %>);
parse_json(stream_json);
google.maps.event.addListener(map, 'zoom_changed', function() {
json_url = "/test?bounds="+map.getBounds()+"&zoom="+map.getZoom();
stream_json = $.getJSON(json_url);
parse_json(stream_json);
});
function parse_json(json) {
if (json.length > 0) {
var markers = [];
for (i=0; i<json.length; i++) {
var place = json[i];
alert(place.longitude +','+place.latitude);
// addLocation(place);
markers[i] = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(place.latitude, place.longitude)
});
}
}
};
}
google.maps.event.addDomListener(window, 'load', initialize);
Many thanks in advance for any pointers you can send our way!
You're not using getJSON correctly. It's an asynchronous call, so you need to supply a callback:
google.maps.event.addListener(map, 'zoom_changed', function() {
json_url = "/test?bounds="+map.getBounds()+"&zoom="+map.getZoom();
$.getJSON(json_url, function(data) {
parse_json(data);
});
});
I have a problem with Google maps API. I'm using V3 API and fancybox for show up map in lightbox-like div. When I click on the link for the first time, fancybox opens and map loads as well. Everything seems to be OK, but when I close the fancybox and try to reopen, the map is loaded wrong..It loads only at about half area than it has to. Something may be wrong with the map object which is created at second time opening. When I am reloading the page each time I want to get correct map, it's ok..Problems coming out when I try to open-close-open-close and so on..Does anybody know what I should to do? I like fancybox, but now I am totaly screwed:)bottom are some pieces of my code..Thanks
$(document).ready(function () {
$("a.maps").fancybox({
'overlayOpacity ': 0.5,
'transitionIn': 'fade',
'transitionOut': 'fade',
'type': 'ajax'
});
});
THIS CONTENT OF THE FANCYBOX. THE LINK IS CALLED FROM SIMPLE a href=""...
function initialize() {
var myLatlng = new google.maps.LatLng(49.095354, 17.749553);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "DAMN"
});
}
function detectBrowser() {
var useragent = navigator.userAgent;
var mapdiv = document.getElementById("map_canvas");
if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1) {
mapdiv.style.width = '100%';
mapdiv.style.height = '100%';
} else {
mapdiv.style.width = '400px';
mapdiv.style.height = '400px';
}
}
initialize();
detectBrowser();
</script>
<div id="mapaOkolo">
<div id="map_canvas"></div>
</div>
Had this problem myself and came up with this workaround:
google.maps.event.addListener(<map object>, 'tilesloaded', function() {
google.maps.event.trigger(<map object>, 'resize');
<map object>.setCenter(<LatLng>);
});
The map is off center so it needs to be centered as well.
This is a very common problem Please take a look here.
Try to use google.maps.event.trigger(map, "resize");
Hope this helps