Map is displaying incorrectly when adding navbar to page - javascript

I have added navbar on a google map page that fetches data from external json file and it is not displaying the map correctly.Also,it says that empty string is passed in getelementbyID in jquery mobile file.Is there a way to fix this?
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas {height: 100%;margin:5% }
</style>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=something&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var myOptions = {
center: new google.maps.LatLng(43.66207, -79.37617),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
$.getJSON('bikeshare.json', function(data) {
$.each( data.stationBeanList, function(i, value) {
var locationLatLong = new google.maps.LatLng(value.latitude, value.longitude);
var marker = new google.maps.Marker({
position: locationLatLong,
map: map,
icon:"img/bike.png",
title:"Bikes available: "+JSON.stringify(value.availableBikes)
});
var infoWindow = new google.maps.InfoWindow({
content:"Docks Available: "+JSON.stringify(value.availableDocks)
});
google.maps.event.addListener(marker, "click", function() {
infoWindow.open(map, marker);
});
});
});
}
</script>
</head>
<body onload="initialize()">
<div data-role="header" >
<h3>BIKESHARE</h3>
<div data-role="navbar" data-position="fixed">
<ul>
<li>Home </li>
<li><a>Reports</a></li>
<li>Locations</li>
<li>Map</li>
</ul>
</div>
</div>
<div data-role="content" id="map_canvas" ></div>
</body>
</html>

This is a CSS issue.
Change this:
#map_canvas {height: 100%;margin:5% }
to:
#map_canvas {height:700px; margin:5%}
Or an alternative would be to calculate a new height and set it before calling the initialize() function:
//Add this line or something similar which calculate div height in the initialize function
$('#map_canvas').css('height', ($(window).height()-10) + 'px');
New Function
function initialize() {
$('#map_canvas').css('height', ($(window).height() - 10) + 'px');
var myOptions = {
center: new google.maps.LatLng(43.66207, -79.37617),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
$.getJSON('bikeshare.json', function (data) {
$.each(data.stationBeanList, function (i, value) {
var locationLatLong = new google.maps.LatLng(value.latitude, value.longitude);
var marker = new google.maps.Marker({
position: locationLatLong,
map: map,
icon: "img/bike.png",
title: "Bikes available: " + JSON.stringify(value.availableBikes)
});
var infoWindow = new google.maps.InfoWindow({
content: "Docks Available: " + JSON.stringify(value.availableDocks)
});
google.maps.event.addListener(marker, "click", function () {
infoWindow.open(map, marker);
});
});
});
}

Related

Google not defined error

I am making a webpage with Google Maps API but I am getting "google not defined error"
How can I get rid of this?
How can I import Google or do something to make this piece of code work?
I want a program in which user will enter location and it shows marker there. but it is not working properly.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<h1>Perform Google Maps Search</h1>
<h3> Please enter the place you want to search</h3>
<input type="text" id="mapsearch" size="50"> <br>
<br>
<div id="map"></div>
<script>
var map;
function initMap() {
var myOptions = {
zoom:14,
navigationControl: true,
scaleControl: true,
panControl: true,
center: new google.maps.LatLng(43.6532,-79.3832),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'),myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(43.6532,-79.3832),
title:"Toronto"
});
marker.setMap(map);
}
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('mapsearch'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function(place) {
var marker = new google.maps.Marker({
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}(place));
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(),12));
});
google.maps.event.addDomListener(window, 'load', init);
</script>
<script src="https://maps.googleapis.com/maps/api/js?key="Your_API_Key"&callback=initMap"
async defer></script>
</body>
</html>
initMap function should be closed at last you are closing it before
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
So you are getting google undefined error.
Also you have add parameter &libraries=places to google map script src
working example
https://plnkr.co/edit/ngtGvuhDDZAnovwPnPXh?p=preview
// Code goes here
var map;
function initMap() {
var myOptions = {
zoom:14,
navigationControl: true,
scaleControl: true,
panControl: true,
center: new google.maps.LatLng(43.6532,-79.3832),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'),myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(43.6532,-79.3832),
title:"Toronto"
});
marker.setMap(map);
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('mapsearch'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function(place) {
var marker = new google.maps.Marker({
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}(place));
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(),12));
});
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<h1>Perform Google Maps Search</h1>
<h3> Please enter the place you want to search</h3>
<input type="text" id="mapsearch" size="50"> <br>
<br>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAtaKPvRV8-ciYtnnzG3QI3CO7m4HJyhaI&libraries=places&callback=initMap"
async defer></script>
</body>
</html>
Most likely your google APIs have not loaded, when your script needs them - hence the "google not defined error". Move this before your script and drop the async defer - or do your script inside a "$( document ).ready"
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAtaKPvRV8-ciYtnnzG3QI3CO7m4HJyhaI&callback=initMap"
async defer></script>

i want to use Map marker from Database

I have a google map and I would like to add a new marker on my database with it latitude and longitude but it's not working and i found some error
"Uncaught SyntaxError: missing ) after argument list" pleses tell me. Thank for helping.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
function initMap() {
var mapOptions = {
center: {lat: 13.847860, lng: 100.604274},
zoom: 10,
}
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
var marker, info;
$.getJSON( "jsondata.php", funtion(jsonObj){
$.each(jsonObj, function(i, item){
marker = new google.maps.Marker({
position: new google.maps.LatLng(item.lat, item.lng),
map: maps,
});
info = new google.maps.Infowindow();
google.maps.event.addListener(marker, 'click', (function(marker, i){
return function() {
info.setContent(item.name);
info.open(maps, marker);
}
})(marker, i));
});
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA6oLvZzDHD-qxeX3g17_uHQMWXFXCxU30&callback=initMap">
</script>
</body>
</html>
and my connect file
<?php
header('Content-Type: application/json');
$objConnect = mysqli_connect("localhost","root","root","username-databasename");
$strSQL = "SELECT * FROM markers ";
$objQuery = mysqli_query($objConnect,$strSQL);
$resultArry = arry();
while($obResult = mysql_fetch_assoc($objQuery))
{
array_push($resultArray,$obResult);
}
echo json_encode($resultArray);
?>
https://i.stack.imgur.com/CLvCe.png
Error on Line 24. It should be like this:
$.getJSON( "jsondata.php", funtion(jsonObj)){
Solution:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
function initMap() {
var mapOptions = {
center: {lat: 13.847860, lng: 100.604274},
zoom: 10,
}
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
var marker, info;
$.getJSON( "jsondata.php", function( jsonObj ) {
$.each(jsonObj, function(i, item){
marker = new google.maps.Marker({
position: new google.maps.LatLng(item.lat, item.lng),
map: maps,
});
info = new google.maps.Infowindow();
google.maps.event.addListener(marker, 'click', (function(marker, i){
return function() {
info.setContent(item.name);
info.open(maps, marker);
}
})(marker, i));
});
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA6oLvZzDHD-qxeX3g17_uHQMWXFXCxU30&callback=initMap">
</script>
</body>
</html>

Open infowindows by default

I have a problem with Google Maps info windows. I have 2 markers and I want to open both info windows by default. But I can't figure out how to do it.
Here is my code:
<html>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=<key>&sensor=false"></script>
<script type="text/javascript">
var locations = [
['loan 1', 46.166621, 8.853315, '<div style="width:250px">text info 1'],
['loan 2', 46.173000, 8.856315, '<div style="width:250px">text info 2'],
];
function initialize() {
var myOptions = {
center: new google.maps.LatLng(46.166621, 8.853315),
zoom: 15,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("default"), myOptions);
setMarkers(map,locations);
}
function setMarkers(map,locations){
var marker, i
for (i = 0; i < locations.length; i++) {
var loan = locations[i][0]
var lat = locations[i][1]
var long = locations[i][2]
var add = locations[i][3]
latlngset = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
map: map, title: loan , position: latlngset
});
map.setCenter(marker.getPosition())
var content = add
var infowindow = new google.maps.InfoWindow()
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
}
}
</script>
</head>
<body onLoad="initialize()">
<div id="default" style="width:100%; height:100%"></div>
</body>
</html>
I tried adding infowindow.open(map,marker); in various place but stil don't work.
Trigger the click-event for the markers.
Put this at the end of the for-loop:
google.maps.event.trigger(marker,'click',{});
working fiddle

calling javascript in infowindow google map

I am trying to call javascript inside google map infoWindow(). I know it's a classic question. I have read a lot of similar question in stackoverflow butI I can't find solution :(
my code:
<!DOCTYPE>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://visapi-gadgets.googlecode.com/svn/trunk/termcloud/tc.css"/>
<script type="text/javascript" src="http://visapi-gadgets.googlecode.com/svn/trunk/termcloud/tc.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Rectangle Overlay</title>
<style type="text/css">
#map {
width:1200px;
height: 700px;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function init() {
var myOptions = {
center: new google.maps.LatLng(38.122404, 23.862591),
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'),myOptions);
var locations = [
['Bondi Beach', 38.6391,23.3437],
["<scr"+"ipt type='text/javascript'>alert('test');</scr"+"ipt>", 37.893, 23.936999999999998]
];
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', init);
</script>
</head>
<body>
<h1>Service</h1>
<h2> Map <h2>
<div id="map"></div>
</script>
</td></tr></table> <div id="chart_div" style="width: 1800px; height: 1100px;"></div> </body>
</html>
anyone know how to solved this issue?
Thank you!
EDIT:
The answer of Jonas Grumannis correct.
In fact the javascript that I need to run is to build a cloudword inside infowindow calling TermCloud() function . I try below code. Any idea please???
<!DOCTYPE>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://visapi-gadgets.googlecode.com/svn/trunk/termcloud/tc.css"/>
<script type="text/javascript" src="http://visapi-gadgets.googlecode.com/svn/trunk/termcloud/tc.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Rectangle Overlay</title>
<style type="text/css">
#map {
width:1200px;
height: 700px;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function init() {
var myOptions = {
center: new google.maps.LatLng(38.122404, 23.862591),
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'),myOptions);
var locations = [
['Bondi Beach', 38.6391,23.3437],
["Hello", 37.893, 23.936999999999998]
];
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
//infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
var yourFunction = new YourFunction(locations[i][0])
}
})(marker, i));
}
var YourFunction = function(str) {
this.init = function() {
google.load("visualization", "1");
google.setOnLoadCallback(draw);
}
this.init();
}
function draw() {
data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
data.addColumn('string', 'Link');
data.addRows(3);
data.setValue(0, 0, 'First Term');
data.setValue(0, 1, 10);
data.setValue(1, 0, 'Second');
data.setValue(1, 1, 30);
data.setValue(1, 2, 'http://www.google.com');
data.setValue(2, 0, 'Third');
data.setValue(2, 1, 20);
var outputDiv = document.getElementById('tcdiv');
var tc = new TermCloud(outputDiv);
tc.draw(data, null);
}
}
google.maps.event.addDomListener(window, 'load', init);
</script>
</head>
<body>
<h1>Service</h1>
<h2> Map <h2>
<div id="map"></div>
</script>
</td></tr></table> <div id="chart_div" style="width: 1800px; height: 1100px;"></div> </body>
</html>
Found a solution -- wrap the infoWindow content in a div and add a listener in the 'domready' event for that div's id (see this SO thread):
var infowindow = new google.maps.InfoWindow({
content: '<div id="myInfoWinDiv">'+ myContent +'</div>'
});
google.maps.event.addListener(infowindow,'domready',function(){
$('#myInfoWinDiv').click(function() {
//Do your thing
});
});
In my example, a click handler is attached to the div using jQuery. You can put any JS in the domready event handler. It needs to be done in the infoWindow's domready, otherwise you can't be certain that the object has been created.
I think calling a function click listener should work (haven't tested it though):
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
var yourFunction = new YourFunction()
}
})(marker, i));
Then, outside all the google maps stuff
var YourFunction = function() {
this.init = function() {
alert("You have clicked a marker");
}
this.init();
}
What about click event in Google Map API V3?
var infowindow = new google.maps.InfoWindow({
content: '<div id="myInfoWinDiv">'+ myContent +'</div>'
});
google.maps.event.addListener(marker, 'click', function(e){
infowindow.open(map, marker);
// Other stuff goes here...
});

How can I get a single marker to update it's position as the user moves?

I'm showing a map with a "Track my Position" button. It starts marking the user's position, but leaves a trail of markers as the user moves. How can I get a single marker to update it's position as the user moves?
<script type="text/javascript">
$( document ).bind( "mobileinit", function() {
$.mobile.allowCrossDomainPages = true;
});
</script>
<script src="../../jquery.mobile.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js? key=AIzaSyCvtEfhi11SeoL1Osfo8St53JRkasYnTRw&sensor=true"></script>
<script src="../../cordova-2.7.0.js"></script>
<script type="text/javascript">
var map;
var image = "../../bbimages/cycling.png";
$(document).on('pageshow', '#fenlandmap', function(){
$(document).on('click', '#”btnInit”', function(){
navigator.geolocation.watchPosition(onMapSuccess, onMapFailure, {enableHighAccuracy:true,timeout:20000});
});
var latlng = new google.maps.LatLng(51.183244, -115.585399);
var myOptions = {
zoom: 15,
streetViewControl: false,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var kmlUrl = 'http://www.sites.google.com/site/skyrokml/kml/FenlandTrail.kml';
var kmlOptions = {
suppressInfoWindows: false,
preserveViewport: true,
map: map
};
var kmlLayer = new google.maps.KmlLayer(kmlUrl, kmlOptions);
});
function onMapSuccess(pos) {
map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
var marker = new google.maps.Marker({
position: map.getCenter(),
icon: image,
map: map,
title: 'Click to zoom'
}); }
function onMapFailure() {
alert('You must have an internet connection to view the maps');
}
</script>
</head>
<body>
<div data-role="page" style="width:100%;height:100%;" id="fenlandmap">
<div data-role="content" style="width:100%;height:100%;" id="map_content">
<div id="map_canvas" style="width:100%; height:448px"></div>
</div><!-- /content -->
<div data-role="footer" data-position="fixed" id="footer" align="center">
<a href="../bbteasyfenlandloop.html" data-role="button" data-direction="reverse"
data-transition="slide"
data-icon="arrow-l">Back</a>
<a href="../../index.html" data-role="button"
data-transition="turn" data-direction="reverse" data-icon="home">Home</a>
<button id=”btnInit” data-icon="star">Track my Position</button>
</div>
</div>
<!-- /page -->
</body>
Move the marker to the global scope. Outside of any function do this:
var marker = null;
Then you have two options:
move the marker if it has already been created.
if (marker == null) {
marker = new google.maps.Marker({
position: map.getCenter(),
icon: image,
map: map,
title: 'Click to zoom'
});
} else {
marker.setPosition(map.getCenter());
}
working example
destroy it and recreate it at the new location.
if (marker && marker.setMap) {
marker.setMap(null);
}
marker = new google.maps.Marker({
position: map.getCenter(),
icon: image,
map: map,
title: 'Click to zoom'
});
working example
The following approach is suggested by me
1)User clicks on botton
2)Marker is placed on map
3)User drag the marker and place it where it wants
Now if the user wants to change its place again he will not click on any button
just he will drag the marker at its new position
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var lat, lng;
var latlng = new google.maps.LatLng(18.5236, 73.8478);
function initialize() {
var myoptions = {
center: latlng,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), myoptions);
function addmarker(latlng) {
var marker = new google.maps.Marker({
position: latlng,
title: 'new marker',
draggable: true,
map: map
});
google.maps.event.addListener(marker, 'dragend', function (evt) {
document.getElementById('current').innerHTML='Latitude : ' + evt.latLng.lat().toFixed(5) + ' Longitude : ' + evt.latLng.lng().toFixed(5);
lat = evt.latLng.lat().toFixed(5); // here you will always get latitude
lng = evt.latLng.lng().toFixed(5); // here you will always get longitude
});
google.maps.event.addListener(marker, 'dragstart', function (evt) {
});
map.setCenter(marker.position);
marker.setMap(map);
}
$('#btnaddmarker').on('click', function () {
addmarker(latlng)
var mapBtn = document.getElementById('btnaddmarker');
mapBtn.disabled = true;
})
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script type="text/javascript">
window.onload = function () {
initialize();
}
</script>
</head>
<body>
<div class="welcome" style="width: 1200px; height:800px; margin: 0px 50px 0px 50px;">
<div>
<button id="btnaddmarker" class="btn btn-primary" style="">add marker</button>
<div id="current" style="float:right">Nothing yet...</div>
</div>
<div>
<div id="googleMap" style="width: 100%; height: 500px; float: left; margin-left: -7px;"></div>
</div>
</div>
</body>
</html>
You will get the current user latitude and longitude at the right side using the above code

Categories

Resources