Map not showing in Cordova Android - google-maps

I have built an Android app using Cordova following these instructions
https://cordova.apache.org/docs/en/latest/guide/cli/index.html
All works well except the map shows when I run emulate browser or emulate android, but not when I install the apk to my J5 Samsung phone.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src 'self' 'unsafe-inline' *; img-src * data: 'unsafe-inline'">
<!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' gap:; style-src 'self' 'unsafe-inline'; media-src *" />
<!-- Good default declaration:
* gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
* https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
* Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
* Enable inline JS: add 'unsafe-inline' to default-src
* Enable eval(): add 'unsafe-eval' to default-src
* Create your own at http://cspisawesome.com
-->
<!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: 'unsafe-inline' https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *" /> -->
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
</head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map { height: 100% }
</style>
<body>
<div class="app">
<h1>PhoneGap</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
</div>
</div>
<div id="geolocation"></div>
<button type="button" onclick="addMarker()">Add Marker</button>
<div id="map">MAP HERE</div>
<script src="/__/firebase/4.13.0/firebase-app.js"></script>
<script src="/__/firebase/4.13.0/firebase-auth.js"></script>
<script src="/__/firebase/4.13.0/firebase-database.js"></script>
<script src="/__/firebase/4.13.0/firebase-messaging.js"></script>
<script src="/__/firebase/4.13.0/firebase-functions.js"></script>
<!-- Leave out Storage -->
<!-- <script src="/__/firebase/4.13.0/firebase-storage.js"></script> -->
<script src="/__/firebase/init.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA8RwcNCgxRCRpiSgiRpr_InT2Vt-aDwPQ" type="text/javascript"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
<script src="https://www.gstatic.com/firebasejs/4.13.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
.............
};
firebase.initializeApp(config);
</script>
And js file
var test=5;
var json = [
{
lat: 55.5,
lng: -4
},
{
lat:56,
lng: -4.5
}
];
var Latitude = undefined;
var Longitude = undefined;
// Get geo coordinates
function getMapLocation() {
navigator.geolocation.getCurrentPosition
(onMapSuccess, onMapError, { enableHighAccuracy: true });
}
// Success callback for get geo coordinates
var onMapSuccess = function (position) {
Latitude = position.coords.latitude;
Longitude = position.coords.longitude;
getMap(Latitude, Longitude);
};
// Get map by using coordinates
function getMap(latitude, longitude) {
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map
(document.getElementById("map"), mapOptions);
var latLong = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: latLong
});
//marker.setMap(map);
map.setZoom(9);
map.setCenter(marker.getPosition());
showMarkers();
}
// Success callback for watching your changing position
var onMapWatchSuccess = function (position) {
var updatedLatitude = position.coords.latitude;
var updatedLongitude = position.coords.longitude;
if (updatedLatitude != Latitude && updatedLongitude != Longitude) {
Latitude = updatedLatitude;
Longitude = updatedLongitude;
getMap(updatedLatitude, updatedLongitude);
}
};
// Error callback
function onMapError(error) {
console.log('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Watch your changing position
function watchMapPosition() {
return navigator.geolocation.watchPosition
(onMapWatchSuccess, onMapError, { timeout: 30000 });
}
function showMarkers(){
for(var i=0;i<json.length;i++) {
data = json[i];
var latLong = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: latLong
});
marker.setMap(map);
}
}
function addMarker(){
var newMarker = new Object();
newMarker["lat"] = Latitude;
newMarker["lng"] = Longitude;
writeCoords("abc",Latitude, Longitude);
json.push(newMarker);
showMarkers();
}
function readMarkers(){
var activeRef = firebase.database().ref('location/');
activeRef.on('value', function(snapshot){
snapshot.forEach(function(childSnapshot) {
alert(childSnapshot.val().latitude);
});
});
}
watchMapPosition();
function writeCoords(userId, lat, lng){
firebase.database().ref('location/' + firebase.database().ref().child('location').push().key).set({
latitude: lat,
longitude: lng
});
}
var app = {
// Application Constructor
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
// deviceready Event Handler
//
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function() {
this.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
app.initialize();
And the config.xml as this can be where problems lie
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.hello" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>HelloWorld</name>
<description>
A sample Apache Cordova application that responds to the deviceready event.
</description>
<author email="dev#cordova.apache.org" href="http://cordova.io">
Apache Cordova Team
</author>
<content src="index.html" />
<plugin name="cordova-plugin-whitelist" spec="1" />
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<platform name="android">
<allow-intent href="market:*" />
</platform>
<platform name="ios">
<allow-intent href="itms:*" />
<allow-intent href="itms-apps:*" />
</platform>
<engine name="android" spec="~6.1.2" />
</widget>
All works fine on emulators and I can upload to Firebase using the marker button. When it moves to the phone itself, I see everything but the map.

Well I did 2 things. Installed cordova plugin add cordova-plugin-geolocation and unplugged the usb from phone after installation. Not sure if both were required, but it works now.

Related

Openlayer2: Can I add more circles on layer without removing last ones?

I have a simple openlayer programm to add circle on mouse click. But for new circle it will remove last ones.I am giving jsfiddel link. kindly update it if you can help. further code is also here .
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script type="text/javascript" src="http://openlayers.org/api/OpenLayers.js"></script>
<link rel="stylesheet" type="text/css" href="http://openlayers.org/en/v3.16.0/css/ol.css">
<style type="text/css">
</style>
<script type='text/javascript'>
//<![CDATA[
$(window).load(function() {
function updateIcon(f) {
vector.drawFeature(f);
}
options = {
div: "map",
zoom: 2,
center: [0, 0],
layers: [
new OpenLayers.Layer.OSM()
]
};
map = new OpenLayers.Map(options);
vector = new OpenLayers.Layer.Vector();
map.addLayer(vector);
var point1 = new OpenLayers.Geometry.Point(0, 0);
var point2 = new OpenLayers.Geometry.Point(5000000, 1000000);
var point3 = new OpenLayers.Geometry.Point(2000000, 2000000);
var radius = $("#amount").val();
var mycircle = OpenLayers.Geometry.Polygon.createRegularPolygon(point2, radius, 20, 0);
var featurecircle = new OpenLayers.Feature.Vector(mycircle);
///vector.addFeatures([featurecircle]);
OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
defaultHandlerOptions: {
'single': true,
'double': false,
'pixelTolerance': 0,
'stopSingle': false,
'stopDouble': false
},
initialize: function(options) {
this.handlerOptions = OpenLayers.Util.extend({}, this.defaultHandlerOptions);
OpenLayers.Control.prototype.initialize.apply(
this, arguments
);
this.handler = new OpenLayers.Handler.Click(
this, {
'click': this.trigger
}, this.handlerOptions
);
},
trigger: function(e) {
console.log(map)
console.log(e)
var lonlat = map.getLonLatFromPixel(e.xy);
var newPoint = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);
vector.removeFeatures([featurecircle]);
var mycircle = OpenLayers.Geometry.Polygon.createRegularPolygon(
newPoint,
radius,
40,
0
);
featurecircle = new OpenLayers.Feature.Vector(mycircle);
vector.addFeatures([featurecircle]);
}
});
var click = new OpenLayers.Control.Click();
map.addControl(click);
click.activate();
}); //]]>
</script>
</head>
<body>
<p>
<input type="text" id="amount" value="1000000" style="border:0; color:#f6931f; font-weight:bold;">
</p>
<div id="slider-range-max"></div>
<div id="map" style="width:600px;height:600px;"></div>
</body>
</html>
http://jsfiddle.net/zLjae81b/30/
Why don't you want to remove while removing it yourself?
Just remove the removing code (line 108):
vector.removeFeatures([featurecircle]);

How to Auto Fill my current address to a search box

Greeting, I'm new to IONIC and now i have met a problem. I'm trying to include a google map direction services in my application. The application now will jump to the location A once i input the address in the search box, but what i want is when i 1st open the app, search box A will automatically get my location address and fill the address in the textbox A.
TaxiServices.html
<div class="bar bar-header bar-dark item item-button-left">
<!--<a class="button icon-left ion-chevron-left button-clear button-dark" ng-click="st.link()">Home Page</a>-->
<button class="button button-clear" ng-click="ts.link()">
<i class="icon ion-arrow-left-c"></i>
</button>
<h1 class="title">Taxi Services TEST</h1>
</div>
<ion-view ng-app="taxiservice" ng-controller="MapController">
<ion-content class="has-footer has-header" scroll="false">
<div class="container">
<div class="titlebar">
<div class="preorder">
<!--http://jsfiddle.net/ucmL2/-->
<ion-checkbox ng-model="ModelData.Animals">Pre-Order</ion-checkbox>
<div class="form-group" ng-show="ModelData.Animals">
<form action="action_page.php">
Date & Time :
<input type="datetime-local" class="datetime">
</form>
</div>
</div>
<div class="places">
<input id="origin-input" class="controls" type="text"
placeholder="Enter an origin location">
<input id="destination-input" class="controls" type="text"
placeholder="Enter a destination location">
</div>
</div>
<div id="map" data-tap-disabled="true"></div>
<div class="fare has-footer">
<h3>Estimated Fare: </h3>
</div>
</div>
taxiservice-ctrl.js
var map;
(function () {
'use strict';
angular
.module('taxiservice.ctrl', [])
.controller('TaxiServiceCtrl', ['$scope', '$ionicPopup', '$timeout', '$rootScope', '$interval', '$window', '$ionicLoading',
function ($scope, $ionicPopup, $timeout,$rootScope, $interval, $window, $ionicLoading) {
//variables
var self = this;
self.link = link;
function link() {
$window.location.href = "../../js/ServiceMenu/index.html";
}
$scope.showPopup = function() {
var alertPopup = $ionicPopup.alert({
title: 'Good News!',
template: 'Yay! We have found you a driver!'
});
alertPopup.then(function(res) {
$window.location.href = "../../js/TaxiFound/index.html";
});
};
}])
.controller('MapController', function ($scope, $ionicLoading) {
google.maps.event.addDomListener(window, 'load', function () {
var origin_place_id = null;
var destination_place_id = null;
var travel_mode = google.maps.TravelMode.WALKING;
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: -33.8688, lng: 151.2195},
zoom: 17
});
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"
});
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(map);
var origin_input = document.getElementById('origin-input');
var destination_input = document.getElementById('destination-input');
var options = {
types: ['geocode'],
componentRestrictions: {country: 'my'}
};
map.controls[google.maps.ControlPosition.TOP_LEFT].push(origin_input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(destination_input);
var origin_autocomplete = new google.maps.places.Autocomplete(origin_input, options);
origin_autocomplete.bindTo('bounds', map);
var destination_autocomplete =
new google.maps.places.Autocomplete(destination_input, options);
destination_autocomplete.bindTo('bounds', map);
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function expandViewportToFitPlace(map, place) {
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
}
origin_autocomplete.addListener('place_changed', function() {
var place = origin_autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
expandViewportToFitPlace(map, place);
// If the place has a geometry, store its place ID and route if we have
// the other place ID
origin_place_id = place.place_id;
route(origin_place_id, destination_place_id, travel_mode,
directionsService, directionsDisplay);
});
destination_autocomplete.addListener('place_changed', function() {
var place = destination_autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
expandViewportToFitPlace(map, place);
// If the place has a geometry, store its place ID and route if we have
// the other place ID
destination_place_id = place.place_id;
route(origin_place_id, destination_place_id, travel_mode,
directionsService, directionsDisplay);
});
function route(origin_place_id, destination_place_id, travel_mode,
directionsService, directionsDisplay) {
if (!origin_place_id || !destination_place_id) {
return;
}
directionsService.route({
origin: {'placeId': origin_place_id},
destination: {'placeId': destination_place_id},
travelMode: travel_mode
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
});
});
})();
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<meta http-equiv="Content-Security-Policy" content="default-src 'self' *; style-src 'self' 'unsafe-inline' *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *">
<title></title>
<link href="../../css/ionic.app.css" rel="stylesheet">
<script src="../../lib/angular/angular.js"></script>
<script src="../../lib/angular-animate/angular-animate.js"></script>
<script src="../../lib/angular-sanitize/angular-sanitize.js"></script>
<script src="../../lib/angular-ui-router/release/angular-ui-router.js"></script>
<script src="../../lib/ionic/js/ionic.js"></script>
<script src="../../lib/ionic/js/ionic-angular.js"></script>
</head>
<body ng-app="taxiservice">
<ion-nav-view>
</ion-nav-view>
<script src="https://maps.googleapis.com/maps/api/js?&callback=&libraries=places&sensor=false">
</script>
<script src="app.js"></script>
<script src="map.js"></script>
<script src="content/taxiservice-ctrl.js"></script>
</body>
</html>
app.js
var app = angular
.module('taxiservice', [
'ionic',
'taxiservice.ctrl'
])
.run(function($ionicPlatform,$timeout) {
$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();
}
});
})
.config(function($ionicConfigProvider,$stateProvider,$urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
templateUrl: 'content/TaxiService.html',
controller:'TaxiServiceCtrl as ts'
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app');
});
I have struggled with this problem very long times, please help!
Look the reverse geocoding example here. You can retrieve the address by using the position which you already have and then add the marker. https://github.com/mapsplugin/cordova-plugin-googlemaps/wiki/geocoder
A good plugin i use on my app for fill Google Maps Autocomplete is
https://github.com/israelidanny/ion-google-place
Easy to install , reverse geocoding included , Great Template
the customization is easy
Good Luck

Google Map doesn't work on OpenShift

I'm using Google Map API to on my website. When I run my web on local host, Google Map work well but when I deploy my web on OpenShift, Google Map doesn't work? I use java web with Tomcat
My index
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="lolkittens" />
<meta charset="utf-8" />
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script src="GoogleMapAPI.js" type="text/javascript" charset="utf-8"></script>
<title>Untitled 2</title>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
My js file:
function initialize()
{
var myCenter=new google.maps.LatLng(10.771400, 106.685844);
var mapProp =
{
center:myCenter,
zoom:17,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker=new google.maps.Marker(
{
position:myCenter,
animation:google.maps.Animation.BOUNCE
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow(
{
content:"NHP Shop <br/> 274/9 Võ Văn Tần P5, Q3"
});
//add sự kiện onclick vào google map marker
/*google.maps.event.addListener(marker, 'click', function()
{
infowindow.open(map,marker);
});*/
infowindow.open(map,marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
So please tell me what wrong with my code? Thanks so much

Getting error when I adding an Overlay WMS

I am new to GIS and I am working on my openLayer tutorial.
Here is HTML code:
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<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" type="text/css" href="css/index.css" />
<title>Hello World</title>
</head>
<body>
<div class="app">
<div style="width:100%; height:100%" id="map"></div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script src="http://openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
Here is JavaScript code:
var app = {
// Application Constructor
initialize: function () {
//this.bindEvents();
var map = new OpenLayers.Map('map');
var wms = new OpenLayers.Layer.WMS("OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0", { layers: 'basic' });
var dm_wms = new OpenLayers.Layer.WMS(
"Canadian Data",
"http://www2.dmsolutions.ca/cgi-bin/mswms_gmap",
{
layers: "bathymetry,land_fn,park,drain_fn,drainage," +
"prov_bound,fedlimit,rail,road,popplace",
transparent: "true",
format: "image/png"
},
{ isBaseLayer: false }
);
var vectorLayer = new OpenLayers.Layer.Vector("Overlay");
var feature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(-71, 4),
{ some: 'data' },
{
externalGraphic: 'img/location_fav.png',
graphicHeight: 21,
graphicWidth: 16
});
vectorLayer.addFeatures(feature);
map.addLayers([wms, dm_wms, vectorLayer]);
map.zoomToMaxExtent();
}
};
View in browser:
I get this error:
http://www2.dmsolutions.ca/cgi-bin/mswms_gmap?LAYERS=bathymetry%2Cland_fn%2…EST=GetMap&STYLES=&SRS=EPSG%3A4326&BBOX=-180,-90,0,90&WIDTH=256&HEIGHT=256 Failed to load resource: net::ERR_NAME_NOT_RESOLVED
If I remove from javascript this rows:
var dm_wms = new OpenLayers.Layer.WMS(
"Canadian Data",
"http://www2.dmsolutions.ca/cgi-bin/mswms_gmap",
{
layers: "bathymetry,land_fn,park,drain_fn,drainage," +
"prov_bound,fedlimit,rail,road,popplace",
transparent: "true",
format: "image/png"
},
{ isBaseLayer: false }
);
I get this view on browser:
Any idea why I get the error above when I try to overlay a layer?
The server "http://www2.dmsolutions.ca/cgi-bin/mswms_gmap" seems to be down , try with another WMS like
http://129.206.228.72/cached/osm
var dm_wms = new OpenLayers.Layer.WMS(
"OSM example",
"http://129.206.228.72/cached/osm?",
{
layers: "osm_auto:all"
transparent: "true",
format: "image/png"
},
{ isBaseLayer: false }
);

geolocation function in jquery mobile

I have this html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<meta name="description" content="" />
<meta name="author" content="Salvatore Mazzarino" />
<meta name="viewport" content="width=device-width; initial-scale=1.0" />
<!-- jquery mobile scripts -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile- 1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<!-- my own style sheet -->
<link rel="stylesheet" href="./assets/css/style.css" type="text/css" />
<!-- google maps api script -->
<script type="text/javascript" src="./includes/js_map.js"></script>
<script src="http://maps.google.com/maps/api/jssensor=false"></script>
</head>
<body>
<div data-role = "page" id = "map-page">
<div data-role = "header">
<h1>Your position</h1>
</div>
<div data-role = "content" id = "map-canvas">
<!-- here the map -->
</div>
</div>
</body>
</html>
and this js file :
$( "#map-page" ).live( "pageinit", function()
{
// Default to Via Messina,Catania,IT when no geolocation support
var defaultLatLng = new google.maps.LatLng(37.530073, 15.112151);
if ( navigator.geolocation )
{
function success(pos)
{
// Location found, show coordinates on map
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail()
{
drawMap(defaultLatLng); // Show default map
}
// Find users current position
navigator.geolocation.getCurrentPosition(success, fail, {enableHighAccuracy:true, timeout: 6000, maximumAge: 500000});
}
else
{
drawMap(defaultLatLng); // No geolocation support
}
function drawMap(latlng) {
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map-canvas"), myOptions);
// Add an overlay to the map of current lat/lng
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Greetings!"
});
}
});
I'm trying to obtain my position.in the html page a mas should appears but nothing apper neither the default map. why? any idea?
Without seeing your live code, it's hard to see if any of the CSS might be causing display issues. However, there are at least two things that need to be fixed:
Your call to the Google Maps API needs to be moved above your own JS file (in the head of the document).
You have an error in your URL that references the Maps API JS file. Change it from:
http://maps.google.com/maps/api/jssensor=false
to:
http://maps.google.com/maps/api/js?sensor=false
I was able to get the map to load and show a marker in the middle of the map.