Uncaught ReferenceError: google is not defined when placing pins - javascript

I keep getting the google is not defined. This only happens when I try to put the pins on the map. The map shows up fine with no errors until I add all the lines after the initMap() function. I have seen similar posts but none of the answers resolved my issue. Thanks for any advice in advance
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="maps.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/tabletop.js/1.5.1/tabletop.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPduELA=" crossorigin="anonymous"></script>
<script type="text/javascript" src="maps.js"></script>
<title>Dr Office Data</title>
</head>
<body>
<div class="pageContainer">
<div id="map"></div>
</div>
<div class="sortContainer">
<button type="button" name="button">Click to Show Summary Markers</button>
<div class="stateDropdown">
<label for="stateList">Select a State</label>
<select class="" name="states">
<option value="ALL">All</option>
<option value="AL">Alabama</option>
<option value="CO">Colorado</option>
<option value="MS">Mississippi</option>
</select>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap"
async defer></script>
</body>
</html>
```
var markerData = [["FIRST","LAST","ADDRESS","PHONE",39.6387797,-104.8007541],["FIRST","LAST","ADDRESS","PHONE",39.6125868,-105.1377128],["FIRST","LAST","ADDRESS","PHONE",30.6940368,-88.0945316]]
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891)
});
}
var infowindow = new google.maps.InfoWindow;
var marker, i;
for (i = 0; i < markerData.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markerData[i][4], markerData[i][5]),
map: map
});;
}
```

Like Geocodezip said, your maps-related code needs to be placed within the callback function to ensure the API has loaded before the code is executed. Try this working jsfiddle. Full code below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<title>Dr Office Data</title>
</head>
<body>
<div class="pageContainer">
<div id="map" style="height:400px;width:400px;"></div>
</div>
<div class="sortContainer">
<button type="button" name="button">Click to Show Summary Markers</button>
<div class="stateDropdown">
<label for="stateList">Select a State</label>
<select class="" name="states">
<option value="ALL">All</option>
<option value="AL">Alabama</option>
<option value="CO">Colorado</option>
<option value="MS">Mississippi</option>
</select>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" async defer></script>
<script>
var markerData = [
["FIRST", "LAST", "ADDRESS", "PHONE", 39.6387797, -104.8007541],
["FIRST", "LAST", "ADDRESS", "PHONE", 39.6125868, -105.1377128],
["FIRST", "LAST", "ADDRESS", "PHONE", 30.6940368, -88.0945316]
];
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891)
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < markerData.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markerData[i][4], markerData[i][5]),
map: map
});
}
}
</script>
</body>
</html>
Hope this helps!

Related

I need advice with making a Google map based app

so I'm trying to make a Google maps app for Android with Phonegap where I could add markers that have like a message. And the message is just stored locally for now. So I included a picture how the app looks now. Here is the App
So osoite means address, Viesti means message and lisää merkintä means add a note.
So here is the HTMl code for the index:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-2.1.4.js"
integrity="sha256-siFczlgw4jULnUICcdm9gjQPZkw/YPDqhQ9+nAOScE4="
crossorigin="anonymous"></script>
<script
src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<title>Kartta</title>
</head>
<body>
<div id="pageOne" data-role="page">
<div data-role="header">
<h1>Kartta</h1>
</div>
<div role="main" class="ui-content ui-body-a">
<div id="geolocation" style="width: 285px; height: 370px;">
</div>
<div role="main" class="ui-content ui-body-a">
<p id="pageOne">
</p>
</div> <!-- /content -->
</div>
<div data-role="footer">
<label for="textinput-hide" class="ui-hidden-accessible">Osoite</label>
<input type="text" class="Osoite" name="textinput-hide" id="textinput-hide" placeholder="Osoite"
<br>
<label for="textinput-hide" class="ui-hidden-accessible">Viesti</label>
<input type="text" class="Viesti" name="textinput-hide" id="textinput-hide" placeholder="Viesti">
<br>
<button class="ui-btn">Lisää merkintä</button>
</div> <!-- /footer -->
</div>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=(My own key)">
</script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
$(document).on("pageOne", "#marker", function () {
$.ajax({
url: "https://maps.googleapis.com/maps/api/geocode/json?address=1600+Ratapihantie,+Pasila,+FI&key=(My own key)",
datatype: "json",
timeout: 5000
})
.done(function(data) {
var marker= results[0].geometry.location.lat
var marker2= results[0].geometry.location.lng
})
});
app.initialize();
</script>
</body>
</html>
And here is the code for the Javascript:
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online',
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
// The scope of 'this' is event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
app.receivedEvent('deviceready');
// Get our current location
navigator.geolocation.getCurrentPosition(app.onSuccess, app.onerror);
},
// Current location was found
// Show the map
onSuccess: function(position) {
var longitude = position.coords.longitude;
var latitude = position.coords.latitude;
var latLong = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
center: latLong,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("geolocation"), mapOptions);
},
// Current location could not be determined
// Show error
onerror: function(error) {
alert('code: ' +error.code + '/n' + 'message: ' + error.message + '\n');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
I just need help with adding the marker with the message.
You can use Google Map API for adding markers in map.
For simple marker, use this code:
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
For more details, Check out:
https://developers.google.com/maps/documentation/javascript/examples/marker-simple

how to display multiple google maps per page

I have a problem when I try to show two maps in more than a view. I hope you can help me.
I have this HTML code:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script><!-- load angular -->
........
<div class="tab-content">
<!-- HOME PAGE -->
<div id="pois" class="tab-pane fade in active">
<div class="panel-body">
<div class="row">
<div class="col-md-8">
<div >
<!-- MAPA -->
<div class="embed-responsive embed-responsive-4by3 embed-responsive-item" style="margin-bottom: 10px;
min-width: 323px; min-height: 323px" id="map_canvas"></div>
</div>
</div>
........
<!-- SEARCH TAB -->
<div class="panel-body">
<div class="col-sm-6">
<form class="form" role="form">
<div class="form-group">
<input type="text" class="form-control" placeholder="Direccion" ng-model="address"/>
<div class="well">
<b>Latitud: {{latitud}}</b><br>
<b>Logitud: {{longitud}}</b>
</div>
</div>
<button ng-click="sacarDir(address)" type="submit" class="btn btn-primary btn-block">Buscar</button><br>
</form>
<!-- MAPA -->
<div class="embed-responsive embed-responsive-4by3 embed-responsive-item" style="margin-bottom: 10px;
min-width: 323px; min-height: 323px" id="map_canvas2"></div>
</div>
.................
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXX&callback=initMap">
</script>
CONTROLLER JS:
angular.module('userManager',[],function($locationProvider){
$locationProvider.html5Mode(true);
});
var map;
var map2;
.................
function initMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: {lat: 40.46366700000001, lng: -3.7492200000000366},
zoom: 6
});
map2 = new google.maps.Map(document.getElementById('map_canvas2'), {
center: {lat: 40.46366700000001, lng: -3.7492200000000366},
zoom: 6
});
$.get('/pois', function(res){
var message=res.message;
if(!res.error){
for(i=0;i<message.length;i++){
var marker = new google.maps.Marker({
position: {lat: message[i].latitud, lng: message[i].longitud},
map: map,
animation: google.maps.Animation.DROP,
title: message[i].nombre
});
// Push marker to markers array
markers.push(marker);
}
}
});
setMarkers(markers);
}
The problem is that the first map (map_canvas) works perfectly, but when I change to the search tab the map doesn't show, only a grey square. Then if I resize the window of explorer I can see the map (map_canvas2) but the other map (map_canvas) stops working. What can I do?
Thanks!!

Delete marker when new marker is added?

I am having a problem deleting user added markers upon a new marker being add. I originally tried to go about the right click method but I only want the user to be able to create one marker at a time. Can someone please help me?
function addMarker(location){
marker = new google.maps.Marker({
position: location,
map: GlobalMap,
draggable: true,
animation: google.maps.Animation.DROP,
clickable: true
});
var form = $("#form").clone().show();
var contentString = form[0];
infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.open(GlobalMap,this);
});
infowindow.open(GlobalMap,marker);
markerPosition = marker.getPosition();
populateInputs(markerPosition);
google.maps.event.addListener(marker, "dragend", function (mEvent){
populateInputs(mEvent.latLng);
});
google.maps.event.addListener(marker, 'rightclick', function(){
marker.setMap(null)
});
}
google.maps.event.addDomListener(window, 'load', window.onload);
function populateInputs(pos){
document.getElementById("latitude").value=pos.lat()
document.getElementById("longitude").value=pos.lng();
}
function clearOverlays(){
for(var i = 0; i <markers.length; i++){
markers[i].setMap(null);
}
}
var markers= [];
var center= null;
var GlobalMap = null;
var marker = null;
var infowindow;
var geocoder = new google.maps.Geocoder();
window.onload = function() {
// Creating a reference to the mapDiv, which is defined in the host html file
var mapDiv = document.getElementById('map');
// Creating a latLng for the center of the map, these coordinates set the center of the initial map to the center of Springfield.
var latlng = new google.maps.LatLng(37.1950, -93.2861);
// Creating an object literal containing the properties
// we want to pass to the map
var options = {
center: latlng,
zoom: 11, // This zoom level shows the OTO area.
mapTypeId: google.maps.MapTypeId.ROADMAP // We want to show the data on the road map, as opposed to the satellite view.
};
// Now Creating the map
GlobalMap = new google.maps.Map(mapDiv, options);
oto.setMap(GlobalMap);
$('#address').keypress(function(e){
if(e.which==13){
e.preventDefault();
window.geocode();
}
});
markers.push(marker);
google.maps.event.addListener(GlobalMap, "click", function (event)
{
addMarker(event.latLng);
});
google.maps.event.addListener(marker, 'dragend', function(marker){
var latLong = marker.latLng;
$latitude.value = latLong.lat();
$longitude.value = latLong.lng();
});
}
Here is the HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Public Comment</title>
<link type="text/css" href="css/style.css" rel="stylesheet" media="all" />
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=drawing&sensor=false"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
var otoTableId = '1gPq1ryMpY1S_ovp6pIl0LvqDJkGNUUGShPpDCxtj';
var GlobalMap = null;
//var Urbanlayer = new google.maps.KmlLayer('http://www.ozarkstransportation.org/GIS/OTOBoundary.kml',{preserveViewport:true, suppressInfoWindows:true});
</script>
<script type="text/javascript" src="js/map.js"></script>
</head>
<body>
<!-- Top Banner Bar !-->
<button onclick="toggle_visibility('checkboxes')" style="float: right;">Toggle legend</button>
<div id="banner"><img src="http://www.ozarkstransportation.org/GIS/OTOgraphicSmall.jpg" border="none" height= "66">
<input type="text" id="address" class="form-control" placeholder="e.g., 205 Park Central East, Springfield MO" size="35">
<span class="input-group-btn">
<button onClick="window.geocode()" class="btn btn-success" value=>
<span class="glyphicon glyphicon-map-marker"></span>Go
</button>
</span>
<em id = "banner_text" align="absmiddle">Left click to drop a marker.<br> Right click to delete most recent marker.<br>Cancel to reset with no markers.</em>
</div>
<!-- The Google Map Window !-->
<div id="map"></div>
<!-- The Layer Toggle Window !-->
<div id="checkboxes">
<h3>Left click to drop a marker.<br> Right click to delete marker.<br>Cancel to reset with no markers.</h3>
<br><input type="checkbox" id="NAME" checked="true" onClick="toggleOto()"/><i class="fa fa-minus"></i>OTO Boundary<br />
<table bgcolor="#FFFFFF"><tr><td>
<br>
<!-- <center><b><font color="#000000">Use "add a marker" tool to leave comment.<br> Drag marker to desired location.</font></b></center> !-->
<br>
<center><font size="-1">
OTO MPO |
<!-- #BeginDate format:Am1 -->August 20, 2015<!-- #EndDate --> |
<a target="_blank" href="http://www.ozarkstransportation.org/GIS/Disclaimer.pdf">Disclaimer</a>
</font><br>
<font size="-2">For best results view in Google Chrome</font><br></center>
</td></tr></table>
</div>
<!-- The Bottom Messaging !-->
<div id="container">
</div>
<div id="entryform">
<form role="form" id = "form">
<iframe id ="myFrame" src="https://docs.google.com/forms/d/1EjeuI7ddocJIUr8RALi_WZIuqgQlfgVG9WMqvKR0lSw/viewform?embedded=true" width="500" height="500" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
<h4>Please copy and paste the Latitude and Longitude values into the above form.</h4>
<div class="form-group">
<label><b>Latitude</b></label>
<input id ="latitude" type="text" class="form-control" name="lat" `enter code here`placeholder="Latitude" required="yes">
</div><br>
<div class="form-group">
<label><b>Longitude</b></label>
<input id ="longitude" type="text" class="form-control" name="lng" placeholder="Longitude" required="yes">
</div><br>
<div class="form-group">
<!-- <button class="btn btn-primary" id="submit-button">Submit</button> !-->
<button class="btn btn-primary" id ="delete-button">Cancel</button>
</div>
</form>
</div>
</body>
</html>
Looks like your marker is already global. This should work:
function addMarker(location){
// check if the marker already exists and has a .setMap method
if (marker && marker.setMap) {
// remove existing marker from the map
marker.setMap(null);
}
// create the marker
marker = new google.maps.Marker({
position: location,
map: GlobalMap,
draggable: true,
animation: google.maps.Animation.DROP,
clickable: true
});
// ... rest of your code

Map view is not loading with PhoneGap

I am developing an iPhone application using PhoneGap and jQueryMobile, in my application I have two html pages, first is index.html page and second is mapView.html, now, my problem is when I open mapView.html from index.html using
function loadMap() {
$.mobile.changePage( "mapView.html", { transition: "pop"} );
}
map is not loading. If I open mapView.html on any browser it works perfectly, even if I load mapView.html directly by changing
self.viewController.startPage = #"mapView.html";
in appDelegate class map loads on screen. Do anyone have any idea why map is not loading when I open it from another .html page?My PhoneGap version is 2.0.0
Thanks.
EDIT 1:mapView.html code
<!DOCTYPE HTML>
<html>
<head>
<title>Map Location</title>
<link rel="stylesheet" href="jquery.mobile-1.1.1.min.css" />
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery.mobile-1.1.1.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">
var demoCenter = new google.maps.LatLng(41,-87);
var map;
function initialize()
{
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 7,
center: demoCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function addMarkers()
{
// perform your AJAX here. In this example the markers are loaded through the cityList array
$.ajax({
type:'post',
url:'test.html',
data:'',
success:function(data)
{
// imagine that the data in this list
// will be retrieved from the AJAX response
// i used the cityList array just for testing
var cityList = [
['Chicago', 41.850033, -87.6500523, 1],
['Illinois', 40.797177,-89.406738, 2]
];
var marker, i;
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < cityList.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(cityList[i][1], cityList[i][2]),
map: map,
title: cityList[i][0]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(cityList[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
});
}
$(document).ready(function()
{
addMarkers();
});
</script>
</head>
<body onload="initialize()">
<div id="basic-map" data-role="page">
<div data-role="header" data-theme="b">
<h1>Map Location</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>
</body>
</html>
The $.mobile.changePage uses the jQuery Mobile AJAX functionality. jQuery Mobile loads only the code which is inside the first data-role="page" element in the DOM.
As stated in the jQuery Mobile docs , in jQuery Mobile, AJAX is used to load the contents of each page into the DOM as you navigate, and the DOM ready handler $(document).ready() only executes for the first page.
Below you can find a working example which includes two pages, the navigation is performed through Ajax and the map is loaded inside the second page:
Also note that you can perform a transition using rel="external" or data-ajax="false". The usage of these attributes will cause a full page refresh without animated transition.
Working Example:
Instructions:
Create a folder
Create a file with name maps.js inside the folder
Create a file with name map-intro.html inside the folder
Create a file with name map.html inside the folder
Fill each one of the created files with the corresponding code which can be found below
Add the below code inside the maps.js:
function initialize() {
var mapCenter = new google.maps.LatLng(59.3426606750, 18.0736160278),
myOptions = {
zoom:10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: mapCenter
},
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
$( document ).on( 'pageshow', '#map-page',function(event){
initialize();
});
$( document ).on( 'click', '#map-anchor', function(event){
event.preventDefault();
$.mobile.changePage( "map.html", { transition: "flip" } );
});
Add the below code inside the map-intro.html:
<!doctype html>
<html lang="en">
<head>
<title>Map Intro Page</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script>
<script src="./maps.js"></script>
</head>
<body>
<div id="map-intro-page" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">Map Example</a></h1>
</div>
<div data-role="content">
<ul data-role="listview" id="my-list">
<li>Go to Map</li>
</ul>
</div>
</div>
</body>
</html>
Add the below code inside the map.html:
<!DOCTYPE html>
<html>
<head>
<title>jQuery mobile with Google maps geo directions example</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
</head>
<body>
<!-- /page -->
<div data-role="page" id="map-page">
<!-- /header -->
<div data-role="header">
<h1>Map</h1>
<a data-rel="back">Back</a>
</div>
<!-- /content -->
<div data-role="content" class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:300px;"></div>
</div>
</div>
</body>
</html>
I hope this helps.

Can not get multiple page jquery mobile working with google maps

I have jQuery mobile working with google maps so that I can display one, stand alone page with a map that takes up the full screen. However, I can't figure out how to make a simple 2 page example where I have a button that takes me to the map.
I'm very confused as to why there is javascript in the body tags on all of the examples. I've been trying to follow the examples here http://jquery-ui-map.googlecode.com/svn/trunk/demos/jquery-google-maps-mobile.html , but it is very hard to figure out what is necessary just for the basic_map within all of the source HTML. I'm new to using jQuery and javascript.
Here is the HTML code that works as a stand alone page.
<!doctype html>
<html lang="en">
<head>
<title>Simple Map</title>
<!--link type="text/css" rel="stylesheet" href="css/style.css" -->
</head>
<body>
<div id="basic_map" data-role="page" class="page-map">
<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>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?&sensor=true"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="./jquery-ui-map-3.0-rc/ui/jquery.ui.map.js"></script>
<!--script type="text/javascript" src="./jquery-ui-map-3.0-rc/demos/js/demo.js"></script-->
<script type="text/javascript">
$(function(){
initializeMap(37.6, -122.1);
});
function initializeMap(lat,lng) {
var adjustedHeight = ($(window).height());
$('#map_canvas').css({height:adjustedHeight});
//$("#map_canvas").height = $(window).height() - $("#header").height() - $("#footer").height();
setTimeout(function() {
var latlng = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom: 9,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
google.maps.event.trigger(map, 'resize');
map.setZoom( map.getZoom() );
}, 500);
}
</script>
</body>
</html>
I've tried implementing the following 2 screen example where I enter in the latitude and longitude on the first page, then I go to a map centered at that point on the next page. However, my map displays under the text boxes (not on a new page as desired) and I get the error:
Uncaught TypeError: Cannot call method 'changePage' of undefined
According to other posts that error has to do with me needing to call the pagecreate function instead of $(document).ready(). I'm not calling either of those functions because I didn't know if they were necessary since I was able to make other simple, multi page mobile web apps without having to wait for other pages to be ready or created.
My multiple screen code that produces the error is
<!doctype html>
<html lang="en">
<head>
<title>Simple Map</title>
<link type="text/css" rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?&sensor=true"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="./jquery-ui-map-3.0-rc/ui/jquery.ui.map.js"></script>
<!--script type="text/javascript" src="./jquery-ui-map-3.0-rc/demos/js/demo.js"></script-->
<script type="text/javascript">
var lat;
var lng;
function plotPoint(){
lat = document.getElementById("lat").value;
lng = document.getElementById("lng").value;
initializeMap(lat,lng);
$.mobile.changePage("#basic_map", "pop");
}
function initializeMap(lat,lng) {
var adjustedHeight = ($(window).height());
$('#map_canvas').css({height:adjustedHeight});
//$("#map_canvas").height = $(window).height() - $("#header").height() - $("#footer").height();
setTimeout(function() {
var latlng = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom: 9,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
google.maps.event.trigger(map, 'resize');
map.setZoom( map.getZoom() );
}, 500);
}
</script>
<!-- Main Page-->
<!-- Start of second page: #viewMap -->
<div data-role="page" id="main" data-theme="c">
<div data-role="header">
<h1>Main Page</h1>
</div><!-- /header -->
<div data-role="content" data-theme="c">
<label for="lat">Latitude:</label>
<input type="text" name="lat" id="lat" value="" />
<label for="lng">Longitude:</label>
<input type="text" name="lng" id="lng" value="" />
Plot this point
</div><!-- /content -->
</div><!-- /viewMap page -->
<div id="basic_map" data-role="page">
<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>
</body>
</html>
In summary, my issues are:
I'm very confused about where I need to place my javascripts. In the first, stand alone page example, if I move the javascript to the head tag, nothing works. Do I need to put javascript in the head AND the body? If so, what goes where?
How do I implement pagecreate in this example and when should I use it in general?
What other things do I need to do to get this basic example working?
Are there pointers to simple, mobile jQuery code without a ton of extra stuff in them?
As stated in the jQuery Mobile docs, in jQuery Mobile, AJAX is used to load the contents of each page into the DOM as you navigate, and the DOM ready handler $(document).ready() only executes for the first page.
jQuery Mobile loads just the code which is inside the first data-role="page" element in the DOM. Therefore in case the navigation is performed through AJAX then the scripts on your second page are not loaded.
You may find below two sample examples of Google Maps in jQuery Mobile.
The first example is a multipage example.
the second example includes two pages, the navigation is performed through Ajax and the map is loaded inside the second page.
Example 1:
<!DOCTYPE html>
<html>
<head>
<title>Map Example Multiple Pages</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery mobile with Google maps</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>
function initialize() {
var mapCenter = new google.maps.LatLng(59.3426606750, 18.0736160278),
myOptions = {
zoom:10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: mapCenter
},
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
$(document).on("pageinit", "#map-page", function() {
initialize();
});
</script>
</head>
<body>
<div data-role="page" id="home-page">
<!-- /header -->
<div data-role="header">
<h1>Maps</h1>
</div>
<!-- /content -->
<div data-role="content">
Click to see the Map
</div>
</div>
<!-- /page -->
<div data-role="page" id="map-page">
<!-- /header -->
<div data-role="header">
<h1>Map</h1>
Home
</div>
<!-- /content -->
<div data-role="content" class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:300px;"></div>
</div>
</div>
</body>
</html>
Example 2:
Instructions:
Create a folder
Create a file with name maps.js inside the folder
Create a file with name map-intro.html inside the folder
Create a file with name map.html inside the folder
Fill each one of the created files with the corresponding code which can be found below
Add the below code inside the maps.js:
function initialize() {
var mapCenter = new google.maps.LatLng(59.3426606750, 18.0736160278),
myOptions = {
zoom:10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: mapCenter
},
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
$( document ).on( 'pageshow', '#map-page',function(event){
initialize();
});
$( document ).on( 'click', '#map-anchor',function(event){
event.preventDefault();
$.mobile.changePage( "map.html", { transition: "flip" } );
});
Add the below code inside the map-intro.html:
<!doctype html>
<html lang="en">
<head>
<title>Map Intro Page</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script>
<script src="./maps.js"></script>
</head>
<body>
<div id="map-intro-page" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">Map Example</a></h1>
</div>
<div data-role="content">
<ul data-role="listview" id="my-list">
<li>Go to Map</li>
</ul>
</div>
</div>
</body>
</html>
Add the below code inside the map.html:
<!DOCTYPE html>
<html>
<head>
<title>jQuery mobile with Google maps geo directions example</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
</head>
<body>
<!-- /page -->
<div data-role="page" id="map-page">
<!-- /header -->
<div data-role="header">
<h1>Map</h1>
<a data-rel="back">Back</a>
</div>
<!-- /content -->
<div data-role="content" class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:300px;"></div>
</div>
</div>
</body>
</html>
I hope this helps.

Categories

Resources