I basically want to have a script on the page which shows a map when it finds two fields on the page named "lng" and "lat" which have a value.
This means that if there are the fields on the page with values, then it will try and display a map, but if not, then it will not.
This is the code I have so far:
http://jsfiddle.net/spadez/xJhmk/3/
function mapDisplay() {
var latval = $('input[id=lat]').val();
var lngval = $('input[id=lng]').val();
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);
}
$(function () {
mapDisplay();
});
I am not very good at jquery at the moment but this is what I tried which didn't work:
if (latval !=NULL && lngval != NULL)){
...my code
}
Can someone with a little more knowledge help me understand why this approach doesn't work please?
Try this
if ( !isNaN(latval) && !isNaN(lngval)) {
So basically it checks if the 2 inputs are numbers, and only if true will step into the if condition.
Also
var latval = $('input[id=lat]').val();
var lngval = $('input[id=lng]').val();
can be safely written as
var latval = $('#lat').val(),
lngval = $('#lng').val();
You can hook up the change event for the inputs that will display the maps
Code
function mapDisplay() {
var latval = $('#lat').val(),
lngval = $('#lng').val();
if (!isNaN(parseFloat(latval)) && !isNaN(parseFloat(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');
}
}
$(function () {
$('input').on('change', mapDisplay).trigger('change');
});
Check Fiddle
You can do this:
var latval = $('#lat').val();
var lngval = $('#lng').val();
if ($.trim(latval) != '' && $.trim(lngval) != '') {
// You code
No need to do this input[id=lat], you can directly call it like $('#lat')
Use $.trim() to remove the whitespace from the beginning and end of a string.
your code is correct : you just have to add a line in you css in order to view the map:
add
display:block; in #map_canvas
like this :
#map_canvas {
display:block;
height: 150px;
width: 300px;
}
moreover you can change its display setting by setting this display property using jquery(depending upon whether variables have values or not.).
by default textbox returns string value. so for empty textbox you can check :
if(latval=='' && lngval==''){alert('blank');}
else{your code;}
the value returned from text box is not a NULL it is just an empty string so you should check whether the value is empty or not
if(latval !="" && lngval !=""){
Your code
}
and if you want to specific for only numbers , try adding
$.isNumeric()
if($.isNumeric(latval) && $.isNumeric(lngval )){
Your code
}
You can access variables like
var lat = jQuery.trim($('#lat').val());
var lng = jQuery.trim($('#lng).val());
And check if the fields were empty
if(lat == '' && lng == '') {
//do code
} else {
//show the map
$("#mapId").show();
}
As you are prob checking latitude/longtitude, I would also check if they are numeric.
function checkValues() {
var valueOK = false;
if($.isNumeric($('#lat').val())) {
if($.isNumeric($('#lng').val())) valueOK = true;
}
return valueOK;
}
$(function () {
if(checkValues) {
mapDisplay();
}
}
Related
I'm using a script (not made by myself) in order to show markers in Google MAP API with Markerclustering. I've included this script to one of my page and since then, my jQuery code doesn't work anymore.
I've started debugging with console etc, and I've found what causes the issue, it's this function that is on the top of the page of the marker_cluster JS script:
<script type="text/javascript" src="speed_test.js"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', speedTest.init);
</script>
<script src="vendors/markerclustererplus/src/markerclusterer.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=speedTest.init">
</script>
function $(element) {
return document.getElementById(element);
}
var speedTest = {};
speedTest.pics = null;
speedTest.map = null;
speedTest.markerClusterer = null;
speedTest.markers = [];
speedTest.infoWindow = null;
speedTest.init = function() {
var latlng = new google.maps.LatLng(39.91, 116.38);
var options = {
// 'zoom': 10,
// 'center': latlng,
// 'mapTypeId': google.maps.MapTypeId.ROADMAP
zoom: 9,
center: new google.maps.LatLng(46.188, 6.12701),
gestureHandling: "greedy",
disableDefaultUI: true,
zoomControl: true,
fullscreenControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
speedTest.map = new google.maps.Map($('map'), options);
speedTest.pics = data.photos;
var useGmm = document.getElementById('usegmm');
google.maps.event.addDomListener(useGmm, 'click', speedTest.change);
var numMarkers = document.getElementById('nummarkers');
google.maps.event.addDomListener(numMarkers, 'change', speedTest.change);
speedTest.infoWindow = new google.maps.InfoWindow();
speedTest.showMarkers();
};
When I comment this portion of code:
function $(element) {
return document.getElementById(element);
}
then my jquery code works back again, but then the Google Map API doesn't show anymore. I think it's because it's a general function... And it must interract with all the function of the page, and that's causing the issue.
You can find this code here.
The file in question here:
If you have any clue how I can fix this issue I'd really appreciate =)
Thank you and have a good day.
$ refers to jQuery and you are changing it by declaring below function
function $(element) {
return document.getElementById(element);
}
Use some other name for function instead of $.Maybe you can use e
function e(element) {
return document.getElementById(element);
}
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
I'm developing a web page with a Google maps application. Currently, I have a functional search bar and map that displays three KML/KMZ layers. I need to be able to toggle between each of the layers, either display one of them, two of them or all three. There is a similar function in Google Earth, but I need it in Google Maps. How can I do this?
Here is my code for the map and search bar:
<script type="text/javascript">
var geocoder;
var map;
var marker;
function initialize() {
geocoder = new google.maps.Geocoder ();
var latlng = new google.maps.LatLng (40.43, -74.00);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
marker = new google.maps.Marker({map:map});
var ctaLayer = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/NY_Radar_data.kmz');
ctaLayer.setMap(map);
var ctaLayer = new google.maps.KmlLayer('http://www.nyc.gov/html/dot/downloads/misc/cityracks.kml');
ctaLayer.setMap(map);
var ctaLayer = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/OKX_Radar_data%20(1).kmz');
ctaLayer.setMap(map);
}
function codeAddress () {
var address = document.getElementById ("address").value;
geocoder.geocode ( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results [0].geometry.location);
marker.setPosition(results [0].geometry.location);
map.setZoom(14);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
It's simply setMap(null) to hide one, setMap(map) to show. I keep a global array variable layers, to keep track of which layer to toggle:
var layers = [];
layers[0] = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/NY_Radar_data.kmz',
{preserveViewport: true});
layers[1] = new google.maps.KmlLayer('http://www.nyc.gov/html/dot/downloads/misc/cityracks.kml',
{preserveViewport: true});
layers[2] = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/OKX_Radar_data%20(1).kmz',
{preserveViewport: true});
The preserveViewport option stops the map from jumping around when the layers are toggled.
Here's the function to toggle:
function toggleLayer(i) {
if(layers[i].getMap() === null) {
layers[i].setMap(map);
}
else {
layers[i].setMap(null);
}
}
Note it's using the global variable. Finally the HTML, you can use checkboxes or buttons, and even a radio button by setting only one active layer at first and enabling the right one when the radio set is updated.
Large weather <input type="checkbox" id="layer0" onclick="toggleLayer(0)" checked>
<input type="button" id="layer1" onclick="toggleLayer(1)" value="Racks">
Small weather <input type="checkbox" id="layer2" onclick="toggleLayer(2)" checked>
The whole demo is here, controls on top left of map: http://jsbin.com/irahef/edit#preview
Heiter's answer is good but a little addition to the code in the jsbin example, if you want to have the layers be undisplayed on initialization is to change
layers[i].setMap(map);
to
layers[i].setMap(null);
and then make sure your checkboxes are unchecked.
I tried the code posted above by Heitor, and noticed that clicking the layers on and off changes the order that they are displayed on the map. I implemented this solution to preserve the order of the layers, but it might be somewhat inefficient. If anyone has any suggestions please share.
function toggleLayer(i) {
var j;
for (j = 0; j < layers.length ; j++ )
{
if (j != i)
{
if (layers[j].getMap() === null)
{
layers[j].setMap(null);
} else {
layers[j].setMap(map);
}
} else { //toggle the selected layer
if (layers[j].getMap() === null)
{
layers[j].setMap(map);
} else {
layers[j].setMap(null);
}
}
}
}
Well I'm having a couple problems getting google maps to work using the v3 API.
Look here: [Removed by Poster]
Both maps are, in fact, working but the zoom level seems like it is random. The zoom is set to 12 when the map is initialized. Also, if you click on the marker, the description box is missing corners and is unable to be closed. Here is the javascript functions I am using to activate these maps:
var mapHash = [];
var bound = new google.maps.LatLngBounds();
finishedCoding = false;
function initMap(map_container_div,lat,lng) {
var latlng = new google.maps.LatLng(lat,lng);
var myOptions = {
zoom:12,
center:latlng,
mapTypeId:google.maps.MapTypeId.ROADMAP,
streetViewControl: false
};
var map = new google.maps.Map(document.getElementById(map_container_div), myOptions);
if (!getMap(map_container_div)) {
var mapInfo = {
mapkey:'',
map:'',
geocoder : new google.maps.Geocoder()
};
mapInfo.map = map;
mapInfo.geocoder = new google.maps.Geocoder();
mapInfo.mapKey = map_container_div;
mapHash.push(mapInfo);
}
}
function placeMarker(myAddress, mapId, description, title) {
mapIndex = getMap(mapId)
//alert(myAddress + mapId + map)
mapHash[mapIndex].geocoder.geocode({
'address':myAddress
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
mapIndex = getMap(mapId)
var marker = new google.maps.Marker({
map:mapHash[mapIndex].map,
position:results[0].geometry.location,
title: title
});
bound.extend(results[0].geometry.location);
mapHash[mapIndex].map.fitBounds(bound);
finishedCoding = true;
placeDesc(marker,description,mapId);
}
});
}
function placeDesc(marker,myDesc,mapId) {
mapIndex = getMap(mapId);
var infowindow = new google.maps.InfoWindow({
content: myDesc
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(mapHash[mapIndex],marker);
});
}
function getMap(mapKey) {
for (var i = 0 ; i < mapHash.length ; i++) {
if (mapHash[i].mapKey == mapKey) {
return i;
}
}
return false;
}
function startmap(mapidd,address,description,title,lat,lng) {
initMap(mapidd,lat,lng)
placeMarker(address,mapidd,description,title)
}
by just removeing
body img {
max-width: 520px !important;
height: auto !important;}
from style sheet
http://www.wppassport.com/wp-content/plugins/easyfanpagedesign/default.theme/style.css
your problem is resolved now
Your dialog boxes aren't closing because of a javascript error.
Something is wrong with infowindow.open(mapHash[mapIndex],marker); inside your click listener. It's displaying the window, which makes you think that the error is happening after, but I'm pretty sure it's in the call itself. When I debugged you weren't making an obvious mistake, but I still think that that line of code is the culprit.
I solved this issue myself and am kicking myself for not thinking of this. :)
Just had to add mapHash[mapIndex].map.setZoom(12);
And I removed the following 2 codes:
bound.extend(results[0].geometry.location);
mapHash[mapIndex].map.fitBounds(bound);