I need advice with making a Google map based app - javascript

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

Related

Can't get pusher to work with angular

I am trying to use pusher and angular together to hit an api over and over again. Sometimes it works and sometimes its doesn't. I am really not sure why.
This is my app.js and html. If anyone can see why it wouldn't be working all the time that would be super helpful! Thank you.
var exampleApp = angular.module('starter', ['ionic', 'pusher-angular'])
exampleApp.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
exampleApp.controller('MyCtrl', ['$scope', '$http', '$pusher', function($scope, $http, $pusher){
//d5e0d23678bdda79bd04
//fa15651bc1ad6c916fc7
var client = new Pusher('d5e0d23678bdda79bd04');
var pusher = $pusher(client);
var issChannel = pusher.subscribe('iss-channel');
// $scope.path = []
// $http.get('/api/location').success(function(data){
// $scope.iss = data;
// });
issChannel.bind('new-location', function(data){
console.log("Receiving event...")
console.log(data);
// $scope.iss = data
// $scope.path.push([$scope.iss.iss_position.latitude, $scope.iss.iss_position.longitude])
});
}]);
exampleApp.controller('MapController', function($scope, $ionicLoading) {
google.maps.event.addDomListener(window, 'load', function() {
var myLatlng = new google.maps.LatLng(37.3000, -120.4833);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
navigator.geolocation.getCurrentPosition(function(pos) {
map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
var myLocation = new google.maps.Marker({
position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
map: map,
title: "My Location"
});
});
$scope.map = map;
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- Jquery -->
<script src="http://code.jquery.com/jquery-1.7.min.js"></script>
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular.min.js"></script>
<!-- pusher-js -->
<script src="//js.pusher.com/3.0/pusher.min.js"></script>
<!-- pusher-angular -->
<script src="//cdn.jsdelivr.net/angular.pusher/latest/pusher-angular.min.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<!-- pusher for bower -->
<!-- <script src="bower_components/dist/pusher.min.js"></script> -->
<script>
var pusher = new Pusher("d5e0d23678bdda79bd04");
pusher.connection.bind('state_change', function() {
$("#conn_status").text(pusher.connection.state);
})
</script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">ISS TRACKER</h1>
</ion-header-bar>
<ion-content ng-controller="MapController">
<div id="map" data-tap-disabled="true"></div>
<div ng-controller="MyCtrl">
latitude: {{ iss.iss_position.latitude }}<br>
longitude: {{ iss.iss_position.longitude }}
</div>
<div>Connection status: <span id="conn_status"></span></div>
</ion-content>
</ion-pane>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyASrLsi0TLN7GvfLzx0lX5rEwQfNzIj5gQ&sensor=true"></script>
</body>
</html>

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

Extension Camera Not Found - Phonegap 3.0

I'm using Phonegap 3 and am testing on a Blackberry 10 device. I cannot get the Camera to work. I added the Camera plugin but when I tap the button in the app to take a picture I get the error
'Failed because: Extension Camera not found.'
When I test in Ripple the errors I get on the console are
'Cannot read property 'PictureSourceType' of undefined' when the page first loads
and
' ReferenceError: Camera is not defined ' when trying to take a picture
config.xml
<?xml version='1.0' encoding='utf-8'?>
<widget id="default.app.id" version="1.0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:rim="http://www.blackberry.com/ns/widgets">
<name>Webworks Application</name>
<author>Your Name Here</author>
<description>
A sample Apache Cordova application that responds to the deviceready event.
</description>
<license href="http://opensource.org/licenses/alphabetical">
</license>
<access subdomains="true" uri="file:///store/home" />
<access subdomains="true" uri="file:///SDCard" />
<access subdomains="true" uri="*" />
<icon src="res/icon/blackberry/icon-80.png" />
<rim:splash src="res/screen/blackberry/splash-1280x768.png" />
<rim:splash src="res/screen/blackberry/splash-720x720.png" />
<rim:splash src="res/screen/blackberry/splash-768x1280.png" />
<content src="index.html" />
<rim:permissions>
<rim:permit>use_camera</rim:permit>
<rim:permit>read_device_identifying_information</rim:permit>
<rim:permit>access_shared</rim:permit>
<rim:permit>read_geolocation</rim:permit>
<rim:permit>record_audio</rim:permit>
<rim:permit>access_pimdomain_contacts</rim:permit>
</rim:permissions>
<feature name="Camera">
<param name="android-package" value="org.apache.cordova.CameraLauncher" />
</feature>
<feature name="NetworkStatus" value="NetworkStatus" />
</widget>
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css">
<link rel="stylesheet" href="css/index.css">
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.3.2.min.js"></script>
<script src="js/mustache.js"></script>
<script src="cordova.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
</head>
<body onload="onLoad()">
<div data-role="page" id="main">
<div data-role="header" class="logo">
<img src="img/logo.png" />
</div>
<div data-role="content">
<ul id="canlist" data-role="listview">
</ul>
New can
</div>
<div data-role="footer" data-theme="c">
<h2 class="offline">Offline Mode</h2>
</div>
</div>
<div data-role="page" id="newcan">
<div data-role="header" class="logo">
<img src="img/logo.png" />
</div>
<div id="candetailcontent" data-role="content">
</div>
<div data-role="footer" data-theme="c">
<p>Snapcan!</p>
</div>
</div>
<script>
var candata = {cantitle:"", candetail:"", canlat:"",canlon:""};
var cantemplate = '<input type="text" name="cantitle" value="{{cantitle}}" placeholder="Can Title"/><textarea cols="40" rows="8" name="candetail" id="candetail" placeholder="Can Detail">{{candetail}}</textarea><input id="addphoto" type="button" data-icon="plus" value="Add a photo" /><img id="canimage" src="{{imagesource}}" /><div id="map">Map Placeholder</div><input id="savecan" type="button" data-theme= "a" value="Save Can"/>';
var lat,long;
var pictureSource; // picture source
var destinationType; // sets the format of returned value
$(document).on("pageinit", function(){
$('#newcan').on('pagecreate', function(event){
var html = Mustache.to_html(cantemplate, candata);
$("#candetailcontent").html(html);
});
$("#newcan").on("pageshow", function(){
navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
});
$("#addphoto").bind("tap", function(){
var options = {sourceType:Camera.PictureSourceType.PHOTOLIBRARY, destinationType: Camera.DestinationType.FILE_URI};
navigator.camera.getPicture(onCameraSuccess, onError, options);
});
});
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
}
// Cordova is loaded and it is now safe to make calls Cordova methods
//
function onDeviceReady() {
console.log("onDeviceReady");
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Handle the online event
//
function onOnline() {
$(".offline").css("visibility", "hidden");
}
function onOffline() {
$(".offline").css("visibility", "visible");
}
function onGeoSuccess(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
var currentposition = new google.maps.LatLng(lat,lon);
var mapoptions = {
zoom: 12,
center: currentposition,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapoptions);
var marker = new google.maps.Marker({
position: currentposition,
map: map
});
}
function onCameraSuccess(imageURI){
$('#canimage').attr("src", imageURI);
$('#canimage').css("display","block");
}
function onGeoError(error){
if(error==1){
alert('Turn on Geolocation services');
}
}
function onCameraError(message){
alert(message);
}
</script>
</body>
</html>
Why can't I access the camera?
please check if >cordova.js is in your www folder else specify the same name as of cordova.js for example <script src="cordova3.0.js"></script>

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