Can't get pusher to work with angular - javascript

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>

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

Not able to get result of Angularjs being displaying as expression in html page

I am newbie in Angularjs and I am trying to work on a google maps application using Angularjs. I am able to generate the expected results apart from one thing. When I included {{loc.co1}} to be printed as a table column. It is not showing the result and giving a null. I searched a lot and found that my appraoch is correct. The results are available in the javascript but then when accessing from html, they dont show up. Could you please help me with this.
The input is when we drawing a rectangle on the map and click on submit, the coordinate values should go into the table.
Also, below is a link of the work I did. Sorry for not following the format properly.
http://plnkr.co/edit/kh5cUJabvG2rPJUEbgyt?p=info
===========code ===================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="ISO-8859-1">
<title>Scientist Entry Map</title>
<link rel="stylesheet" href="ScientistMapPage.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" integrity="sha384-3ceskX3iaEnIogmQchP8opvBy3Mi7Ce34nWjpBIwVTHfGYWQS9jwHDVRnpKKHJg7" crossorigin="anonymous"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDVgNI2snXEm8Cu5y-dxk0Y1ep9Iv3SOC4&libraries=drawing,geometry,places" async defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
<!-- <script type="text/javascript" src="lodash.min.js"></script> -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<!-- <script src="https://code.angularjs.org/1.4.8/angular-route.min.js"></script> -->
<!-- <script type="text/javascript" src="angular.min.js"></script> -->
<!-- <script type="text/javascript" src="angular-google-maps.min.js"></script> -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-google-maps/2.3.3/angular-google-maps.min.js"></script> -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="ng-map.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="MapController" class="form-control">
<table>
<tr><td><h1>Map for selecting places</h1></td></tr>
<tr><td>
<input id="placeSearch" class="form-control" type="text" placeholder="Search Box">
<div id="map"></div>
<button class="btn btn-primary" type="reset" id="btnResetRect" placeholder="ResetMap">Reset Map</button>
<button class="btn btn-primary" type="submit" id="btnSubmitRect">Submit Location</button>
<input type="hidden" id="txtCoords">
<input type="text" id="text" value="{{locationsData[0].co1}}"/>
</td>
<td>
<table class="table table-striped table-bordered">
<tr>
<th>Place
</th>
<th>Coordinates-1
</th>
<th>Coordinates-2
</th>
<th>Coordinates-3
</th>
<th>Coordinates-4
</th>
<th>Delete</th>
</tr>
<tr ng-repeat="loc in locationsData">
<td>to be added</td>
<td>{{loc.co1}}</td>
<td>{{loc.co2}}</td>
<td>{{loc.co3}}</td>
<td>{{loc.co4}}</td>
<td><button type="submit" class="btn btn-primary" id="deleteLocation">Delete</button></td>
</tr>
</table>
</td></tr>
</table>
</div>
</body>
</html>
// Code goes here
var myApp = angular.module('myApp',[]);
myApp.controller('MapController',function($scope) {
$scope.rectShape;
$scope.locationsData =[];
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(25, 80),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
$scope.drawingMg = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
//google.maps.drawing.OverlayType.MARKER,
//google.maps.drawing.OverlayType.CIRCLE,
google.maps.drawing.OverlayType.POLYGON,
//google.maps.drawing.OverlayType.POLYLINE,
google.maps.drawing.OverlayType.RECTANGLE
]
},
polygonOptions: {
fillColor: '#BCDCF9',
fillOpacity: 0.5,
strokeWeight: 2,
strokeColor: '#57ACF9',
clickable: false,
editable: true,
draggable : true,
zIndex: 1
},
rectangleOptions:
{
fillColor: 'red',
fillOpacity: 0.5,
strokeWeight: 2,
strokeColor: 'red',
clickable: true,
editable: true,
draggable:true,
zIndex: 1
}
});
var c1,c2,c3,c4;
google.maps.event.addListener($scope.drawingMg, 'rectanglecomplete', function(rectangle) {
//document.getElementById('info').innerHTML += "rectangle points:" + "<br>";
$scope.rectShape= rectangle;
c1 = rectangle.getBounds().getNorthEast().lat() +"," +rectangle.getBounds().getNorthEast().lng();
c2 = rectangle.getBounds().getNorthEast().lat()+"," +rectangle.getBounds().getSouthWest().lng();
c3 = rectangle.getBounds().getSouthWest().lat()+"," +rectangle.getBounds().getNorthEast().lng();
c4 = rectangle.getBounds().getSouthWest().lat()+"," +rectangle.getBounds().getSouthWest().lng();
document.getElementById("txtCoords").innerHTML = c1 +"\n"+c2+"\n"+c3+"\n"+c4;
// alert(document.getElementById("txtCoords").innerHTML.toString());
//document.getElementById("info").innerHTML += ne +"," +sw+ "<br>";
});
$scope.drawingMg.setMap($scope.map);
$scope.clearButton = document.getElementById("btnResetRect");
$scope.map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push($scope.clearButton);
$scope.submitButton = document.getElementById("btnSubmitRect");
$scope.submitButton.onclick = function(){
alert(c1 +""+c2);
//$scope.locationsData =[];
$scope.locationsData.push({
co1 : c1,
co2: c2,
co3: c3,
co4: c4
});
alert($scope.locationsData.length);
// $scope.locationsDatac1 = c1;
// $scope.locationsDatac2 = c2;
// $scope.locationsDatac3 = c3;
// $scope.locationsDatac4 = c4;
alert($scope.locationsData[0].co1);
};
console.log("outside do click");
$scope.clearButton.onclick = function(){
if($scope.drawingMg.getDrawingMode()){
$scope.shape.setMap(null);
//$scope.shape.setBounds(null);
//$scope.drawingMg.getDrawingMode().setMap(null);
}
};
$scope.placeSearch = document.getElementById("placeSearch");
$scope.searchBox = new google.maps.places.SearchBox($scope.placeSearch);
$scope.map.controls[google.maps.ControlPosition.TOP_LEFT].push($scope.placeSearch);
$scope.map.addListener('bounds_changed', function () {
$scope.searchBox.setBounds($scope.map.getBounds());
});
$scope.markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
$scope.searchBox.addListener('places_changed', function () {
$scope.places = $scope.searchBox.getPlaces();
if ($scope.places.length == 0) {
return;
}
// Clear out the old markers.
$scope.markers.forEach(function (marker) {
marker.setMap(null);
});
$scope.markers = [];
var center;
$scope.places.forEach(function (place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
$scope.markers.push(new google.maps.Marker({
map: $scope.map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds = place.geometry.viewport;
} else {
bounds = place.geometry.location;
}
});
$scope.map.fitBounds(bounds);
});
});
You need to use ng-model in input,
<input type="text" id="text" ng-model="location" />
I have made some necessary changes, no it works
DEMO

Maps markers duplicates appearing because of http.get angular foreach

I am new to angularjs and javascript. I decided to give this project a try to try and get familiar with these technologies.
I am able to get the markers to create on the first page load but when I add a marker or delete a marker it reloads all of the markers that are stored in the database.
I have the refreshPage(); to be able to not have to refresh the page every time a marker is added or deleted but the angular.foreach is causing it to reload every marker including the ones that are shown on the map.
Is there a better method to do this. I tried putting the angular for each in another http.get and then having a createmarker(item) but that did not work. Which would be the best way to handle this an array, another method, or something else?
Any help is appreciated.
controller.js
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function ($scope, $http) {
var count = 1;
$http.get('/locations').success(function (data) {
angular.forEach(data.items, function (item) {
createMarker(item);
});
});
var refreshPage = function() {
$http.get('/locations').success(function (data) {
$scope.items = data.items;
});
$scope.item = "";
};
refreshPage();
$scope.addLocation = function(){
$http.post('/locations', $scope.item);
refreshPage();
};
$scope.removeLocation = function(id){
$http.delete('/locations/'+id).success(function(response){
refreshPage();
});
};
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(41.5, -73),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (info) {
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.lat, info.long),
title: info.city
});
marker.content = '<div class="infoWindowContent">' + info.desc + '</div>';
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
$scope.openInfoWindow = function (e, selectedMarker) {
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
}]);
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&language=en"></script>
<link rel="stylesheet" href="public/css/maps.css">
<title>My Contact Book</title>
</head>
<body ng-controller="AppCtrl">
<div class="container">
<h1>map here</h1>
<div>
<div id="map"></div>
<div id="repeat" ng-repeat="marker in markers | orderBy : 'title'">
<a id="country_container" href="#" ng-click="openInfoWindow($event, marker)">
<label id="names" >{{marker.title}}</label></a>
</div>
</div>
<div>
<h1>My Contact Book</h1>
{{ greeting }}
<table class="table">
<thead>
<tr>
<th>City</th>
<th>State</th>
<th>Description</th>
<th>Latitude</th>
<th>Longitude</th>
<th>Action</th>
<tbody>
<tr>
<td><input class="form-control" ng-model="item.city"></td>
<td><input class="form-control" ng-model="item.state"></td>
<td><input class="form-control" ng-model="item.desc"></td>
<td><input class="form-control" ng-model="item.lat"></td>
<td><input class="form-control" ng-model="item.long"></td>
<td><button class="btn-primary" ng-click="addLocation()">Add Location</button></td>
</tr>
<tr ng-repeat="item in items">
<td>{{item.city}}</td>
<td>{{item.state}} </td>
<td>{{item.desc}} </td>
<td>{{item.lat}}</td>
<td>{{item.long}}</td>
<td><button class="btn btn-danger" ng-click="removeLocation(item.desc)">Delete</button></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-resource.js"></script>
<script src="/controllers/controller.js"></script>
</body>
</html>
You need to remove them before adding more, set to null the map on each one of the markers:
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
chek this link for more information:
https://developers.google.com/maps/documentation/javascript/examples/marker-remove

How to make Angularjs ui map pan on drag?

When using angular-ui-map or angular-google-map libraries the map does not pan on drag even when the mapOptions are set to implicitly do so. Are there any known issues?
code to reproduce-
Scripts
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&libraries=drawing,places,weather&sensor=false"></script>
<script type="text/javascript" src="Scripts/angular.js"></script>
<script type="text/javascript" src="Scripts/angular-ui-event.js"></script>
<script type="text/javascript" src="Scripts/angular-ui-map.js"></script>
Angular-
var Angular = angular.module('LocqusAngular', ['ui.router', 'ui.map', 'ui.event'])
Angular.controller('MapController', function ($scope) {
$scope.markers = [];
$scope.taskMarkers = [];
$scope.bounds = new google.maps.LatLngBounds();
var DefaultLatLng = new google.maps.LatLng(37.09024, -95.712891);
$scope.mapOptions = {
zoom: 4,
center: DefaultLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggable:true
}
html-
<form runat="server">
<asp:ToolkitScriptManager ScriptMode="Release" ID="TSM" EnablePageMethods="true" CombineScripts="true" runat="server">
<Services>
<asp:ServiceReference Path="~/Service.asmx" />
</Services>
</asp:ToolkitScriptManager>
<div id="MapRow" ng-controller="MapController">
<div id="map_canvas" class="map-container" ui-map="map" ui-options="mapOptions"></div>
</div>
</form>

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.

Categories

Resources