First of all, i've already seen the other answers about problems like this, but thats a little different.
So, i have a javascript code that takes longitude and latitude datas from a db via php, i'm actually able to collect the datas in the at-least-looks-correct format, but when i try to update the layer, nothing gets showed... all kinds of help would be appreciated.
Here is the js code:
EDITED, NOW WORKING
var Datas = [new google.maps.LatLng(32.7603282,46.343451)];
var pointArray = new google.maps.MVCArray(Datas);
$(document).ready(function() {
$('#gnome').change(function() {
var inpval=$(this).val();
$.ajax({
url: 'php/query.php',
type: 'POST',
data: {valor : inpval},
success: function(data) {
while(Datas.length > 0) {
Datas.pop();
}
//heatmap.setData(reboot(data));
pointArray = new google.maps.MVCArray(reboot(data));
initialize();
}
});
});
});
var config = {
"radius": 30,
"element": "heatmapEl",
"visible": true,
"opacity": 40,
"gradient": { 0.45: "rgb(0,0,255)", 0.55: "rgb(0,255,255)", 0.65: "rgb(0,255,0)", 0.95: "yellow", 1.0: "rgb(255,0,0)" }
};
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(32.7603282, 46.343451),
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
pointArray = new google.maps.MVCArray(Datas);
heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray
});
heatmap.setMap(map);
}
function reboot(Ddatas){
alert(Ddatas);
var arraino = [];
for (a in Ddatas) {
arraino.push(new google.maps.LatLng(
Ddatas[a][0],
Ddatas[a][1]));
}
alert(arraino);
return (arraino);
}
google.maps.event.addDomListener(window, 'load', initialize);
quite working link http://testingme.altervista.org/progettolpw/index.php
You are not creating the google.maps.LatLng objects correctly.
This is not correct (it makes a string "new google.maps.LatLng(xxx,yyy)", which will not work the way you are expecting):
for (a in Ddatas){
arraino.push("new google.maps.LatLng("+Ddatas[a]+")");
}
Do this instead:
for (a in Ddatas) {
arraino.push(new google.maps.LatLng(
Ddatas[a][0],
Ddatas[a][1]));
}
working fiddle
Related
I am using webservice to load markers from sql server. and a cluster-er to group those markers, then I re-size the map to fit the bounds using map.fitBounds(bounds).. it works fine on chrome and firefox,, BUT not working on IE,, it gives me an error of Out of stack space in one of google map api 3 files (main.js)
you can check this demo for the issue : http://aprilit.com/gmap/default.aspx
here is a part of my code.
function LoadMap(arrMarkers) {
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var markers = [];
var tempCount = 0;
var bounds = new google.maps.LatLngBounds();
for (var XMLCount = 0; XMLCount < arrMarkers.length; XMLCount++) {
var Points = $.parseXML(arrMarkers[XMLCount]);
$Markers = $(Points).find("Marker");
for (var i = 0; i < $Markers.length; i++) {
var tempID = $Markers.find('mid')[i].innerHTML;
var tempCID = $Markers.find('cid')[i].innerHTML;
var myLatLng =
new google.maps.LatLng($Markers.find('lt')[i].innerHTML,
$Markers.find('lg')[i].innerHTML);
markers.push(new google.maps.Marker({
position: myLatLng,
map: map,
animation: google.maps.Animation.DROP,
markerid: $Markers.find('mid')[i].innerHTML,
catid: $Markers.find('cid')[i].innerHTML,
icon: LoadIcon($Markers.find('cimg')[i].innerHTML)
}));
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
google.maps.event.addListener(markers[tempCount], 'click', function () {
infowindow.setContent('<div ><img src="img/assets/loader.gif"/>
Loading../div>');
infowindow.open(map, this);
$.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Markers.asmx/GetMarker",
data: JSON.stringify({ MarkerID: this['markerid'],
CategoryID: this['catid'] }),
dataType: "json",
success: function (msg) {
infowindow.setContent(formatInfoDivHTML(msg.d));
}
});
map.panTo(this.getPosition());
infowindow.open(map, this);
});
bounds.extend(myLatLng);
tempCount++;
}
}
//////////////////////////Here is the problem
map.fitBounds(bounds);
var mcOptions = { gridSize: 50, maxZoom: 12 };
var markerCluster = new MarkerClusterer(map, markers, mcOptions);
google.maps.event.trigger(map, 'resize');
}
thanks and ill appreciate your help
also note that I am using fitbounds in other places and it is working just fine.
Just for the reference,, when I checked with an older version of google chrome (Version 31.0.1650.57 m) it gave me the same error..but when I updated chrome the issue has gone
Your SplitXML function is appending an extra null element to the array of markers. Most versions of IE don't like that.
I solved this issue,,
It appears that IE doesn't support the innerHTML property I used here:
$Markers.find('mid')[i].innerHTML
or any where else where I am retrieving the data from my xml fields.
so it had to be replaced with the the textContent property as this:
$Markers.find('mid')[i].textContent;
and that solves the whole issue.!!
thanks for your help guys
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.
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
Would somebody please advise me as to what I'm doing wrong with this piece of code?
I am currently using a simple JSON file to provide data for info windows using the Google maps V3 API. I am aware of the concept of closures but cannot seem to understand why the info windows are still displaying the last result on click.
Here is my JSON file:
{ "markers": [
{
"lat": 51.5001524,
"lng": -0.1262362,
"firstName": "nameOne"
},
{
"lat": 55.8656274,
"lng": -4.2572227,
"firstName": "nameTwo"
},
{
"lat": 43.834526782236814,
"lng": -37.265625,
"firstName": "nameThree"
}
] }
Here is my JS:
(function(){
function initialize() {
var latlng = new google.maps.LatLng(51.5001524, -0.1262362)
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
function parseJson(){
$.ajax({
url: 'assets/js/markers.json',
dataType: 'json',
success: function(data) {
processMarkers(data)
},
error: function (data) {
console.log('fail')
}
})
}
function processMarkers(data){
var totalMarkers = data.markers.length;
for(i=0;i<totalMarkers;i++){
var latitude = data.markers[i].lat;
var longditude = data.markers[i].lng;
var putMarker = new google.maps.LatLng(latitude, longditude);
var thisMarker = new google.maps.Marker({
position: putMarker,
map: map
});
var firstName = data.markers[i].firstName;
var infoWindow = new google.maps.InfoWindow({
position: putMarker,
content: firstName
});
new google.maps.event.addListener(
thisMarker,
'click',
buildHandler(map, thisMarker));
}
function buildHandler(map, marker){
return function(){
infoWindow.open(map, marker);
};
}
}
parseJson();
}
$(document).ready(function(){
initialize();
});
})();
Any help would be greatly appreciated.
Cheers
infoWindow is some var in the processMarkers scope. That iterates over the same infoWindow over and over for every marker, orphaning it after the last iteration (and leaving it set to the final marker). The orphan cannot die because it's captured in the closure of your click handler. I do not know the google api well enough to predict what's supposed to happen on .open(). But infoWindow doesn't look good at that point...
EDIT: In fact, it seems to me that every infoWindow but the last falls victim to the garbage collector. Or is it referenced somewhere? I cannot make it out.
EDIT: Remember, JS does NOT have {} scopes (like eg C). It only has functional scopes !! In other words, simply pass infoWndow into your buildHandler().