Google Maps api show grey screen - javascript

I am trying to get on my website the gmaps with few markers but i am getting the grey screen or partially grey screen.Before, I used google maps API the same way and everythings works fine. If you can help me I would be grateful.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Zadanie 7</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDPAizH-vug5nDhwYi0C5Km-pCiQRx7wpY"></script>
</head>
<body>
<div class="container-fluid" id="map" style="height: 500px;">
</div>
<div class="container-fluid">
<div class="row content">
<div class="col-sm-3 sidenav">
<h4>Zadanie 6 Martin Kranec</h4>
<ul class="nav nav-pills nav-stacked">
<li>Prvá Stránka</li>
<li>Druhá Stránka</li>
<li class="active">Tretia Stránka</li>
</ul><br>
</div>
<div class="container-fluid">
<div class='container-fluid'><div class='table-responsive'><table class='table'><thead><tr><th>Vlajka</th><th>Štát</th><th>Počet Navštevníkov</th></tr></thead><tbody><tr><td>World</td><td>World</td><td>2</td></tr><tr><td><img class='flag' src='http://www.geonames.org/flags/x/sk.gif'></td><td><a href='countrystatistics.php?countrycode=sk'>Slovensko</a></td><td>2</td></tr></tbody></table></div></div> </div>
</div>
</div>
<footer class="container-fluid">
<p>&COPY;Martin Kranec Webové technológie</p>
</footer>
<script type='text/javascript'>
var lat=[];
var lon=[];
lat.push(48.15);
lon.push(17.1167);
lat.push(48.1704);
lon.push(17.4209);
</script>
<script>
function initMap() {
//alert(lat[1]);
var mapProp = {
center: new google.maps.LatLng(89, -25),
zoom: 4,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapProp);
var count = lat.length;
for (var i = 0; i < count; i++) {
var myLatLng = {lat: lat[i], lng: lon[i]};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: ''
});
}
}
initMap();
//initMap();
</script>
<!--<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDPAizH-vug5nDhwYi0C5Km-pCiQRx7wpY&callback=initMap"></script>-->
</body>
</html>
and here is my website where I work on this project http://147.175.98.165/zadanie7/thirdpage.php

Google maps has a lot of race conditions. I use this code a lot to display them instead. This code should be in a ready event like jquery ready.
new Promise(function (resolve, reject) {
if (!document.getElementById('google-maps')) {
var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
var link = "https://maps.googleapis.com/maps/api/js?key=AIzaSyDPAizH-vug5nDhwYi0C5Km-pCiQRx7wpY&callback=mapsFinishedLoading";
fileref.setAttribute("async", "async");
fileref.setAttribute("defer", "defer");
fileref.setAttribute("src", link);
fileref.setAttribute("id", 'google-maps');
window.mapsFinishedLoading = resolve;
document.getElementsByTagName("body")[0].appendChild(fileref);
} else {
resolve();
}
}).then(function (result) {
//Your map should be available now
mapOptions={};//put your options here
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
});
Make sure your map div is visible before calling
var map = new google.maps.Map(document.getElementById('map'), mapOptions);

Related

Google map content not displaying inside Bootstrap modal part 2

Hello Stackoverflow Coders, I have created another google map with a form input that collects users address and populates it on a map. I have followed a correction created in this link below
Google map content not showing inside Bootstrap modal view
but still yet I cannot get the map to display inside a modal view. If run it on a normal page it will be okay.
can someone help me with that?
Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://maps.google.com/maps/api/js?libraries=places&region=ng&language=en&sensor=true&key=AIzaSyAlb3bRgk_Jq3mBzgpVyLTeeKL-RKaSkx4"></script>
</head>
<body>
<div class="container">
<h2>Google Map</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open MAP</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<br> Address:
<input id="searchTextField" type="text" size="50" style="">
<br>
<div id="test" style="height: 300px;width: 100%;margin: 0.6em;"></div>
<!-- MAP -->
<script type="text/javascript">
$(function getMap() {
var lat = 13.034118,
lng = 77.5679959;
latlng = new google.maps.LatLng(lat, lng),
image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png';
//zoomControl: true,
//zoomControlOptions: google.maps.ZoomControlStyle.LARGE,
var mapOptions = {
center: new google.maps.LatLng(lat, lng),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_left
}
},
map = new google.maps.Map(document.getElementById('test'), mapOptions),
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image
});
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, {
types: ["geocode"]
});
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(autocomplete, 'place_changed', function(event) {
infowindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
moveMarker(place.name, place.geometry.location);
$('.MapLat').val(place.geometry.location.lat());
$('.MapLon').val(place.geometry.location.lng());
});
google.maps.event.addListener(map, 'click', function(event) {
$('.MapLat').val(event.latLng.lat());
$('.MapLon').val(event.latLng.lng());
infowindow.close();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"latLng": event.latLng
}, function(results, status) {
console.log(results, status);
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
var lat = results[0].geometry.location.lat(),
lng = results[0].geometry.location.lng(),
placeName = results[0].address_components[0].long_name,
latlng = new google.maps.LatLng(lat, lng);
moveMarker(placeName, latlng);
$("#searchTextField").val(results[0].formatted_address);
}
});
});
function moveMarker(placeName, latlng) {
marker.setIcon(image);
marker.setPosition(latlng);
infowindow.setContent(placeName);
//infowindow.open(map, marker);
}
});
</script>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Tiles may not load if your map canvas is invisible when map is initializd.But you can trigger tiles loading by using resize.Since you are using you need to first store a reference to map object.
map = new google.maps.Map(document.getElementById('test'), mapOptions),
tmp = map;
And call resize event on map when your modal gets shown
$('#myModal').on('shown.bs.modal', function () {
google.maps.event.trigger(tmp, 'resize')
})

Google Maps not being displayed, JavaScript IntelXDK

I am using Intel XDK to try and get the google maps displayed on the screen at the location set in Intel XDK. However, I am having issues with actually displaying the map on the screen, after spending many hours researching trying to figure out why it isn't working I have hit a brick wall and I have no idea how to proceed from here.
So any help will be greatly appreciated to point me in the right direction, thanks in advance.
Index.html class
<!DOCTYPE html>
<html>
<!--
* Please see the included README.md file for license terms and conditions.
-->
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="jqm/jquery.mobile-min.css">
<title>Blank App Designer Cordova Web App Project Template</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<!-- <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1"> -->
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=no">
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes, minimum-scale=1, maximum-scale=2"> -->
<style>
100% ; } #viewport { width: 100vw ; min-zoom: 100% zoom: 100% ; }
#-ms-viewport { user-zoom: fixed ; min-zoom: 100% ; } #viewport { user-zoom: fixed ; min-zoom: 100% ; }
</style>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" type="text/css" href="css/index_main.less.css" class="main-less">
<!-- <script src="lib/mc/hammer.js"></script> -->
<!-- <script src="lib/ft/fastclick.js"></script> -->
<script src="cordova.js" id="xdkJScordova_"></script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
<!-- <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>-->
<script src="https://maps.googleapis.com/maps/api/js?key=MyApiKey&callback=initMap"></script>
<script src="js/app.js"></script>
<script src="js/Maps.js"></script>
<script type="application/javascript" src="lib/jquery.min.js"></script>
<script type="application/javascript" src="jqm/jquery.mobile-min.js" data-ver="0"></script>
<script type="application/javascript" src="js/index_user_scripts.js"></script>
<script type="application/javascript" src="sidebar/js/hammer.js"></script>
<script type="application/javascript" src="sidebar/js/jquery.hammer.js"></script>
<script type="application/javascript" src="sidebar/js/swipe-hammer.js"></script>
<script type="application/javascript" src="sidebar/js/sidebar.js"></script>
<script type="application/javascript" src="xdk/ad/jqm_subpage.js"></script>
</head>
<body id="afui" class="v2" onload="navigator.geolocation.getCurrentPosition(onSuccess, onError)">
<!-- IMPORTANT: Do not include a weinre script tag as part of your release builds! -->
<!-- Place your remote debugging (weinre) script URL from the Test tab here, if it does not work above -->
<!-- <script src="http://debug-software.intel.com/target/target-script-min.js#insertabiglongfunkynumberfromthexdkstesttab"></script> -->
<div class="upage vertical-col left" id="mainpage" data-role="page"><a class="widget uib_w_2 d-margins" data-uib="jquery_mobile/button" data-ver="0" data-role="button" id="maps" href="#Maps" data-transition="fade">Maps</a>
<a class="widget uib_w_3 d-margins" data-uib="jquery_mobile/button" data-ver="0" data-role="button" id="gps">GPS</a>
</div>
<div class="upage" id="Maps" data-role="page" >
<div class="upage-outer" >
<div class="upage-content ac0 content-area vertical-col left" id="page_70_37"><a class="widget uib_w_4 d-margins" data-uib="jquery_mobile/button" data-ver="0" data-role="button">Button</a>
<div id="map" style="height: 500px; width: 300px; margin: 0; padding: 0;">
</div>
<div data-role="footer" data-position="fixed" class="container-group inner-element uib_w_6" data-uib="jquery_mobile/footer" data-ver="0">
<h1>footer</h1>
<div class="widget-container wrapping-col single-centered"></div>
<div class="widget-container content-area horiz-area wrapping-col left"></div>
<div class="widget-container content-area horiz-area wrapping-col right"></div>
</div>
</div>
<div class="outer-element uib_w_5 uib_crossbar botbar fixed bar-bg thumb-bg bar-gutter" data-uib="layout/bottom_crossbar" data-ver="1" data-anim="{'style':'overlap', 'v':400, 'side':'bottom', 'dur':500}">
<div class="sidebar-content content-area vertical-col">
</div>
</div>
</div>
</body>
</html>
App.js
var latitude;
var longitude;
var onSuccess = function(position) {
alert(
latitude = position.coords.latitude;
longitude = position.coords.longitude;
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
var locationOptions = {
maximumAge: 10000,
timeout: 6000,
enableHighAccuracy: true
};
Maps.js
function initMap() {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'),{
zoom: 16,
center: new google.maps.LatLng(latitude,longitude)//{latitude, longitude}
});
//var marker = new google.maps.marker({position: LatLng, map:map});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('right-panel'));
/* // stops the text directions when un commented
var control = document.getElementById('floating-panel');
control.style.display = 'block';
map.controls[google.maps.ControlPosition.TOP_CENTER].push(control);
*/
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('start').addEventListener('change', onChangeHandler);
document.getElementById('end').addEventListener('change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var start = new google.maps.LatLng(latitude,longitude)//{latitude, longitude};
var end = '10 Downing Street, Downing Street, London';
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
Index_User_Scripts
/*jshint browser:true */
/*global $ */(function()
{
"use strict";
/*
hook up event handlers
*/
function register_event_handlers()
{
/* button Button */
$(document).on("click", ".uib_w_1", function(evt)
{
/* your code goes here */
});
/* button #maps */
$(document).on("click", "#maps", function(evt)
{
/*global activate_page */
activate_page("#Maps");
initMap();
//calculateAndDisplayRoute();
});
/* button #gps */
$(document).on("click", "#gps", function(evt)
{
navigator.geolocation.getCurrentPosition(onSuccess, onError);
});
}
document.addEventListener("app.Ready", register_event_handlers, false);
})();
You need to have permission to use Google API. I used the Google Maps widget and tried with two locations, Statue of Liberty and Taj Mahal. I was able to make it work in emulator as well as on the Intel XDK Preview apps on my phones. Details are in this post:
http://hodentekmobile.blogspot.com/2016/07/intel-xdk-controls-6-using-google-map.html
Here are the settings I used for the widget:

how to refresh div tag with onclick button event using jquery

I downloaded this code on google map using jquery mobile from this site. when i run this code direct on the browser, it works but when i called it from another page it display every other content on the page except the google map unless i reload the page. now i need to manually refresh the google map div in the code below when button is clicked using juery eg.
<div id="map_canvas" style="height:300px;" id1="show"></div>
below is the entire code
<!DOCTYPE html>
<html>
<head>
<title>jQuery mobile with Google maps geo directions example</title>
<meta content="en" http-equiv="content-language">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script>
<script type="text/javascript">
$(document).on("pageinit", "#map_page", function() {
initialize();
});
$(document).on('click', '#submit', function(e) {
e.preventDefault();
calculateRoute();
});
var directionDisplay,
directionsService = new google.maps.DirectionsService(),
map;
function initialize()
{
directionsDisplay = new google.maps.DirectionsRenderer();
//var mapCenter = new google.maps.LatLng(21.5255962, 39.167697299999986);
var mapCenter = new google.maps.LatLng(59.3426606750, 18.0736160278);
var myOptions = {
zoom:10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: mapCenter
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directions"));
}
function calculateRoute()
{
var selectedMode = $("#mode").val(),
start = $("#from").val(),
end = $("#to").val();
if(start == '' || end == '')
{
// cannot calculate route
$("#results").hide();
return;
}
else
{
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
$("#results").show();
/*
var myRoute = response.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
alert(myRoute.steps[i].instructions);
}
*/
}
else {
$("#results").hide();
}
});
}
}
</script>
</head>
<body>
<div data-role="page" id="map_page">
<div data-role="header">
<h1><a href="#">jQuery mobile - Google maps directions service</h1>
</div>
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:300px;" id1="show"></div>
<div data-role="fieldcontain">
<label for="from">From</label>
<input type="text" id="from" value="Goteborg, Sweden"/>
</div>
<div data-role="fieldcontain">
<label for="to">To</label>
<input type="text" id="to" value="Stockholm, Sweden"/>
</div>
<div data-role="fieldcontain">
<label for="mode" class="select">Transportation method:</label>
<select name="select-choice-0" id="mode">
<option value="DRIVING">Driving</option>
<option value="WALKING">Walking</option>
<option value="BICYCLING">Bicycling</option>
</select>
</div>
<input type="button" value="Reload Page" />
<a data-icon="search" data-role="button" href="#" id="submit">Get directions</a>
</div>
<div id="results" style="display:none;">
<div id="directions"></div>
</div>
</div>
</div>
</body>
</html>
Have you tried this?
In your
$(document.ready(function() {
$('#button_click_id').click(function(){
//your code
});
});
Try this.
$("#button_id'").click(function(){ initialize(); });

Google map api v3 shows half a map?

I'm doing a project in Jquery Mobile and having a problem with the Google API. When I navigate to the MapPage from diffrent page the MapPage by itself shows the map OK, but when moving from the HomePage to MapPage it only shows half of the map. If I manually refresh or resize map it will fix it - but I've tried map.resize() without luck so I need a different solution.
I've attached my HTML code of the HomePage and MapPage below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="description" content="Project - Mobile" />
<meta name="author" content="Yuval Vardi" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RentAcar</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<script src="JS/jquery-2.0.2.js"></script>
<script src="JS/jquery.mobile-1.3.1.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="JS/mapScript.js" > </script>
</head>
<body>
<div id="HomePage" data-role="page" data-add-back-btn="true">
<div data-role="header">
</div>
<div data-role="content">
Trip Info
</div>
<div data-role="footer" class="mainFooter">
<h2> © Copyright Yuval Vardi </h2>
<p class="yearNow"> </p>
</div>
</div>
<div id="calculate" data-role="page" data-add-back-btn="true">
<div data-role="header">
</div>
<div data-role="content">
<table id="mapTable">
<tr>
<td>
<p>Pickup location</p>
</td>
<td></td>
<td>
<p>Where do you go?</p>
</td>
</tr>
<tr>
<td>
<input id="startInput" type="text" value="" placeholder="Start location" />
</td>
<td></td>
<td>
<input type="text" id="end" placeholder="Return location"/>
</td>
</tr>
<tr>
<td data-role="controlgroup">
<button id="myLocation" onclick="getMarker()" data-role="button" data-theme="e" > Find me </button>
</td>
<td></td>
<td data-role="controlgroup">
<button onclick="calcRoute()" data-theme="b" > Calculate rout </button>
</td>
</tr>
<tr>
<td colspan="3">
<div id="map-canvas" style="width:400px; height:280px;">
</div>
</td>
</tr>
</table>
</div>
<div data-role="footer" class="mainFooter">
<h2> © Copyright Yuval Vardi </h2>
<p class="yearNow"> </p>
<a class="ui-btn-right" href="#HomePage" data-role="button" data-icon="home" data-iconpos="top" >Home</a>
</div>
</div>
</body></html>
My javascript file:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var israel = new google.maps.LatLng(32.0938254, 34.7786934); // the var for our initial point
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: israel // where to center the map on initial!
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
initialize();
var start = document.getElementById('startInput').value;
var end = document.getElementById('end').value;
var distanceInput = document.getElementById("distance");
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
}
});}
google.maps.event.addDomListener(window, 'load', initialize);
function getMarker() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
}
function showPosition(position) {
var lat=position.coords.latitude;
var long=position.coords.longitude;
marker(lat,long); //calls the marker function
}
function showError(error)
{
alert ("Error loading map");
}
function marker(lat,long) {
var myLatlng = new google.maps.LatLng(lat,long);
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
$("#startInput").attr("value",myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"You are Here!"
});
}
The map div has zero width. To use a percentage width, you have to define the width of all its parents (or at least up to a fixed size element that can be used to compute the width).
See Mike Williams' Google Maps API v2 tutorial page on percentage sizing
You need to call checkResize() API function. Like This:
map = new google.maps.Map(document.getElementById("map"), mapOptions);
map.checkResize()
This one worked for me as well

jQuery mobile add new markers to an existing map

I am working with the jQuery mobile google maps example here, focusing on the first "Basic Map Example".
http://jquery-ui-map.googlecode.com/svn/trunk/demos/jquery-google-maps-mobile.html
I want to be able to dynamically add markers to the basic_map, but I am having some trouble. I'm new to jQuery mobile and JavaScript.
Here is my edited version of the basic-map example from the jQuery mobile UI website. If you save it in the jQuery mobile demos folder, then everything should render properly. I have added a button at the bottom of the map page and also the addMarkers function. When you load the page, the map shows up centered at the mobileDemo coordinates (-41, 87), which is close to chicago, but not quite there. When you click on the button, I want to update the map with another marker at the chicago point, but the screen goes blank.
This is just a mock example of what I really want to do. In my longer, more complicated program, I'm querying a database to find addresses that match the query, then I want to put those markers up on the map dynamically. What do I need to change about this source code to be able to plot the Chicago point (or other markers on the fly)?
<!doctype html>
<html lang="en">
<head>
<title>jQuery mobile with Google maps - Google maps jQuery plugin</title>
<link type="text/css" rel="stylesheet" href="css/jquery-mobile-1.0/jquery.mobile.css" />
<link type="text/css" rel="stylesheet" href="css/mobile.css" />
<script type="text/javascript" src="js/modernizr-2.0.6/modernizr.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript" src="js/jquery-1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-mobile-1.0/jquery.mobile.min.js"></script>
<script type="text/javascript" src="js/jquery.ui-1.8.15/jquery.ui.autocomplete.min.js"></script>
<script type="text/javascript" src="js/demo.js"></script>
<script type="text/javascript" src="../ui/jquery.ui.map.js"></script>
<script type="text/javascript" src="../ui/jquery.ui.map.services.js"></script>
<script type="text/javascript" src="../ui/jquery.ui.map.extensions.js"></script>
<script type="text/javascript">
var mobileDemo = { 'center': '41,-87', 'zoom': 7 };
var chicago = new google.maps.LatLng(41.850033,-87.6500523);
var map
function addMarkers(){
map = new google.maps.Map(document.getElementById('map_canvas'));
var marker = new google.maps.Marker({
map: map,
position: chicago
});
}
$('#basic_map').live('pageinit', function() {
demo.add('basic_map', function() {
$('#map_canvas').gmap({'center': mobileDemo.center, 'zoom': mobileDemo.zoom, 'disableDefaultUI':true, 'callback': function() {
var self = this;
self.addMarker({'position': this.get('map').getCenter() }).click(function() {
self.openInfoWindow({ 'content': 'Hello World!' }, this);
});
}});
}).load('basic_map');
});
$('#basic_map').live('pageshow', function() {
demo.add('basic_map', function() { $('#map_canvas').gmap('refresh'); }).load('basic_map');
});
</script>
</head>
<body>
<div id="basic_map" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a> examples</h1>
<a data-rel="back">Back</a>
</div>
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:350px;"></div>
</div>
</div>
<div data-role="content">
Add Some More Markers
</div>
</div>
</body>
</html>
Please check the below example.
In the first map load there isn't any marker. When you click the button then a marker is dynamically added without a need for page or map refresh.
<!doctype html>
<html lang="en">
<head>
<title>jQuery mobile with Google maps - Google maps jQuery plugin</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"> </script>
<script type="text/javascript" src="http://jquery-ui-map.googlecode.com/svn/trunk/ui/min/jquery.ui.map.min.js"></script>
<script type="text/javascript">
var chicago = new google.maps.LatLng(41.850033,-87.6500523),
mobileDemo = { 'center': '41,-87', 'zoom': 7 };
function initialize() {
$('#map_canvas').gmap({ 'center': mobileDemo.center, 'zoom': mobileDemo.zoom, 'disableDefaultUI':false });
}
$(document).on("pageinit", "#basic-map", function() {
initialize();
});
$(document).on('click', '.add-markers', function(e) {
e.preventDefault();
$('#map_canvas').gmap('addMarker', { 'position': chicago } );
});
</script>
</head>
<body>
<div id="basic-map" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a> examples</h1>
<a data-rel="back">Back</a>
</div>
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:350px;"></div>
</div>
Add Some More Markers
</div>
</div>
</body>
</html>
The initial map:
The map after the button's click:

Categories