jQuery Mobile - Google navigation - Directions Service - Current position identification - jquery-mobile

I have a JQuery Mobile website that people use with their Android device.
(This website mainly deals with clients information.)
I've been looking to integrate a "GET DIRECTION" feature.
I was wondering if it's possible to open Google Navigation app (because it can be used as a GPS, voice navigation) with the current location and one client's address through JQM ?
If not, does anyone has any suggestion?

The official W3C site informs about the W3C Geolocation working group and the milestones that have been set.
You can find here a fresh (May 2012) W3C draft proposal for the Geolocation API.
Below you can find a sample working example that I created. The code finds the current position and provides a direction service. There is a textbox where you can write the target destination and a button which "Get Directions". When you click the button a list at the end of the page is filled with the directions.
You can modify it in order to fit your needs. Furthermore you can find more information about the directions service in the Google Map JavaScript API Directions Service.
<!doctype html>
<html lang="en">
<head>
<title>jQuery mobile with Google maps</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.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 map;
var currentPosition;
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
function initialize(lat, lon)
{
currentPosition = new google.maps.LatLng(lat, lon);
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 15,
center: currentPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
//directionsDisplay.setPanel($("#instructions-content"));
var currentPositionMarker = new google.maps.Marker({
position: currentPosition,
map: map,
title: "Current position"
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(currentPositionMarker, 'click', function() {
infowindow.setContent("Current position: latitude: " + lat +" longitude: " + lon);
infowindow.open(map, currentPositionMarker);
});
}
function locError(error)
{
alert("The position or the map could not be loaded.");
}
function locSuccess(position)
{
initialize(position.coords.latitude, position.coords.longitude);
}
$(document).ready(function()
{
navigator.geolocation.getCurrentPosition(locSuccess, locError);
$("#directions-button").click(function(){
var targetDestination = $("#target-dest").val();
if (currentPosition && currentPosition != '' && targetDestination && targetDestination != '')
{
var request = {
origin:currentPosition,
destination:targetDestination,
travelMode: google.maps.DirectionsTravelMode["DRIVING"]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setPanel(document.getElementById("instructions-content"));
directionsDisplay.setDirections(response);
// For debuging reasons uncomment
/*
var myRoute = response.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
alert(myRoute.steps[i].instructions);
}*/
}
});
}
else
{
alert("The target destination is empty or the current position could not be located.");
}
});
});
</script>
</head>
<body>
<div id="basic-map" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a> examples</h1>
</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 data-role="fieldcontain">
<label for="name">Target Destination:</label>
<input type="text" name="target-dest" id="target-dest" value="" />
</div>
Get Directions
<div data-role="collapsible" id="instructions-container">
<h3>Instructions</h3>
<p><div id="instructions-content"></div></p>
</div>
</div>
</div>
</body>
</html>
Put the HTML code in a file map.html and open it directly with Mozilla Firefox (in case you don't want to put it on a server and test it). Otherwise put the file on a server and open it with any browser you want.
Initially you will be asked whether you want to share your current location. After you press the Share button you will see a map with a marker showing your current position. If you click the marker you will see you latitude and longitude.
I hope this helps.

Related

How to show google map in MVC?

I want to show Google map on my website and my codes are below but after my page loaded in browser i got this error:
Oops! Something went wrong.
This page didn't load Google Maps correctly. See the JavaScript console for
technical details.
I looked at it in Chrome and found this:
Google Maps API error: MissingKeyMapError
https://developers.google.com/maps/documentation/javascript/error-
messages#missing-key-map-error
what is MissingKeyMap?
my codes:
in header tag:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<link href="~/Content/Site.css" rel="stylesheet" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?
sensor=false"></script>
<script type="text/javascript">
function initialize() {
var canvas = $("#map_canvas");
var latitude = 35.78334;
var longitude = 51.42511;
var latlng = new google.maps.LatLng(latitude, longitude);
var options = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(canvas[0], options);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map
});
}
$(function () {
initialize();
});
</script>
On my view :
<div style="width: 100%; height: 100%">
<div id="map_canvas" style="width:100%; height:100%; margin-left: 100px"></div>
</div>
In your js code for google maps, you may find something like this https://maps.googleapis.com/maps/api/js?key=YOURKEYHERE&callback=initMap
Replace YOURKEYHERE with a google API key of your own. Go to this link to get a key of your own and replace it with YOURKEYHERE and it should work fine.
It's all explained here.
https://developers.google.com/maps/documentation/javascript/get-api-key
You need to provide a api-key in the url of your javascript
<script async defer src="https://maps.googleapis.com/maps/api/js? key=YOUR_API_KEY&callback=initMap" type="text/javascript"></script>

How to show longitude and latitude in map using jquery mobile +phonegap (android)

I am able to get longitude and latitude in phonegap .Now i need to show this on map view .Is there any jquery or phonegap library to show in map? I need jquery mobile code so that it will run on both android as well as in Ios.
var lng = 0;
//A button click will call this function
function getLocation() {
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: true });
}
// onSuccess Geolocation
//
function onSuccess(position) {
//Lat long will be fetched and stored in session variables
//These variables will be used while storing data in local database
lat = position.coords.latitude;
lng = position.coords.longitude;
// alert('Lattitude: ' + lat + ' Longitude: ' + lng);
sessionStorage.setItem('lattitude', lat);
sessionStorage.setItem('longitude', lng);
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}var lng = 0;
//A button click will call this function
function getLocation() {
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: true });
}
// onSuccess Geolocation
//
function onSuccess(position) {
//Lat long will be fetched and stored in session variables
//These variables will be used while storing data in local database
lat = position.coords.latitude;
lng = position.coords.longitude;
// alert('Lattitude: ' + lat + ' Longitude: ' + lng);
sessionStorage.setItem('lattitude', lat);
sessionStorage.setItem('longitude', lng);
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
It is extremely easy when working with jQuery Mobile + a small Google framework called GMAP API v3.
Working example: http://jsfiddle.net/Gajotres/7kGdE/
CSS is important here because data-role="content" will by default not cover whole page so we need to force it to cover available space.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-theme="a" data-role="header">
<h3>
First Page
</h3>
</div>
<div data-role="content" id="content">
<div id="map_canvas" style="height:100%"></div>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>
First Page
</h3>
</div>
</div>
</body>
</html>
CSS:
#content {
padding: 0;
position : absolute !important;
top : 40px !important;
right : 0;
bottom : 40px !important;
left : 0 !important;
}
Javascript:
$(document).on('pageinit', '#index',function(e,data){
// This is the minimum zoom level that we'll allow
var minZoomLevel = 12;
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
});
You can make use of the Google Maps JavaScript API. You'll be able to include a map in your application just using JavaScript and HTML. All the info to accomplish this is here. And if you want to show the actual position of the coordinates, you can insert a maker

How to use javascript to query fusion table

I'm having a quite bit of difficulty creating some functions for my fusion tables. I have two tables here:
Points
Parcels
I'm trying to create a number of functions:
1) I want to be able to select the points layer using a drop down menu to select by its ID number.
2) I want to create a function where when I pick my point, I can tell fusion tables to find me the parcels that are within 1km of the point. It would preferable if I can change the distances, so I can do searches for 5km for example.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<style>
#map-canvas { width:500px; height:400px; }
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
var layerl0;
var layerl1;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(43.94255650099583, -79.53326251471042),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layerl0 = new google.maps.FusionTablesLayer({
query: {
select: "'col2'",
from: '1-6QDLUk0Xw7weaB0GP1nmgwvXUuaXJCxWEYbO8E'
},
map: map,
styleId: -1,
templateId: -1
});
layerl1 = new google.maps.FusionTablesLayer({
query: {
select: "'col2'",
from: '1BdIN39m70Vo6Sq0Y5lm1s_4Crh1CZpSwRbYMfnM'
},
map: map,
styleId: -1,
templateId: -1
});
}
function changeMapl0() {
var searchString = document.getElementById('search-string-l0').value.replace(/'/g, "\\'");
layerl0.setOptions({
query: {
select: "'col2'",
from: '1-6QDLUk0Xw7weaB0GP1nmgwvXUuaXJCxWEYbO8E',
where: "'description' CONTAINS IGNORING CASE '" + searchString + "'"
}
});
}
function changeMapl1() {
var searchString = document.getElementById('search-string-l1').value.replace(/'/g, "\\'");
layerl1.setOptions({
query: {
select: "'col2'",
from: '1BdIN39m70Vo6Sq0Y5lm1s_4Crh1CZpSwRbYMfnM',
where: "'description' = '" + searchString + "'"
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div style="margin-top: 10px;">
<label>Zone: </label><input type="text" id="search-string-l0">
<input type="button" onclick="changeMapl0()" value="Search">
</div>
<div style="margin-top: 10px;">
<label>SPP_ID: </label>
<select id="search-string-l1" onchange="changeMapl1(this.value);">
<option value="">--Select--</option>
<option value="<html xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<head>
<META http-equiv="Content-Type" content="text/html">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body style=
Thanks for your help!
Check out the Fusion Tables API Reference, particularly ST_DISTANCE. It looks like what you'll want to do is first geocode each parcel in the fusion table itself (add an address field or lat/long columns and run the built-in geocoder), then you can SELECT with WHERE ST_DISTANCE(location_column, point_location) <= max_distance
On a separate note, you might want to consider leaving HTML formatting out of the fusion table - that's typically something you put in the application/template rather than the data source (for example, imagine if you wanted to use that same data source for
Currently Fusion Tables does not support to use the location column of one table to run spatial queries on another (at least I don't know of this possibility). But still you can achieve what you want, by converting your points to a geometry and then run a spatial query with ST_INTERSECTS on your parcels table.
Steps:
Get the lat/lng values from the point the user clicked on. Either from your Fusion Table or directly from the click event of the map:
GEvent.addListener(map, "click", function(overlay, latLng) {
var lat = latLng.lat(),
lng = latLng.lng();
});
Here is a complete example of getting the lat/lng values from the map.
Use this lat/lng values to update the query of the parcels layer
layer.setOptions({
query: {
select: location
from:
where: 'ST_INTERSECTS(circle(latlng(lat,lng),radius), location)
}
});
See the circle example of Fusion Tables.

How do I save the position of draggable & resizeable elements?

I'm building a site which allows users to create an html page which can then be saved and shared on another site. I want them to be able to resize and drag the page elements. I can do this using jQuery, but I'm not sure how I then save that so that when the page is viewed elsewhere, it looks the same.
I haven't decided yet how to store the page info, but what I'm thinking is that I can store each element in the database along with its absolute position, and its contents. Does that sound like a good plan?
If so, how do I get the position for the div to pass to the php so that it can be saved?
Thanks.
JQueryUI Resizable has an event called resize that you can use:
var resposition = '';
$('#divresize').resizable({
//options...
resize: function(event,ui){
resposition = ui.position;
}
});
The same occurs with JQueryUI Draggable and its event drag:
var dragposition = '';
$('#divdrag').draggable({
// other options...
drag: function(event,ui){
dragposition = ui.position;
}
});
resposition and dragposition is going to be arrays. You can see it working here: http://jsbin.com/uvuzi5
EDIT: using a form, you can save dragposition and resposition into hidden inputs
var inputres = '<input type="hidden" id="resposition" value="'+resposition.left+','+resposition.top+'"/>'
$('#myform').append(inputres);
var inputdrag = '<input type="hidden" id="dragposition" value="'+dragposition.left+','+dragposition.top+'"/>'
$('#myform').append(inputdrag);
And in your PHP file to handle the form:
$dragposition = $_GET['dragposition'];
$resposition = $_GET['resposition'];
$dragposition = explode(',',$dragposition);
$resposition = explode(',',$resposition);
Finally, both variables should be arrays with top and left attributes:
$dragposition => [top,left] attributes from draggable
$resposition => [top,left] attributes from resizable
you have to save position at some where so that you can get position
details when next time you open page.
option 1: you can store html elements position details in "localStorage" its default browser storage.
Example: Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dashboard</title>
<!-- jQuery -->
<script src="vendor/jquery/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="dist/css/jquery-ui.min.css">
<script src="dist/js/jquery-ui.min.js"></script>
</head>
<body>
<script>
var positions = JSON.parse(localStorage.positions || "{}");
$(function() {
var d = $("[id=draggable]").attr("id", function(i) {
return "draggable_" + i
})
$.each(positions, function(id, pos) {
$("#" + id).css(pos)
})
d.draggable({
containment: "#wrapper",
scroll: false,
stop: function(event, ui) {
positions[this.id] = ui.position
localStorage.positions = JSON.stringify(positions)
}
});
});
</script>
<div id="wrapper">
<div id="draggable" class="ui-widget-content draggable" style="height:100px;width:100px;float:left">Div1</div>
<div id="draggable" class="ui-widget-content draggable" style="height:100px;width:100px;float:left">Div2</div>
<div id="draggable" class="ui-widget-content draggable" style="height:100px;width:100px;float:left">Div3</div>
</div>
</body>
</html>
option 2: you can store html elements position details in "your database"

YouTube video in a Google Map Info Window

I am trying to put a youtube video into a Google Map (v3) Info Window.
It works fine in Firefox and Internet Explorer.
It does not work in Safari and Chrome. In those browsers the positioning is off and the video doesn't move when you move the map. The video also gets chopped sometimes.
Here is the code that doe
<!doctype html>
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var map;
function initialize() {
latlng = new google.maps.LatLng(33.4222685, -111.8226402)
myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),myOptions)
var point = new google.maps.LatLng(33.4222685, -111.8226402);
var marker = new google.maps.Marker({
position: point,
map: map
})
google.maps.event.addListener(marker, "click", function(){
bubble = new google.maps.InfoWindow({
content: '<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/UmFjNiiVk9w?fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/UmFjNiiVk9w?fs=1" type="application/x-shockwave-flash" width="425" height="344" allowscriptaccess="always" allowfullscreen="true"></embed></object>'
})
bubble.open(map, marker);
})
}
</script>
</head>
<body onload="initialize();">
<div id="map" style="width: 984px; height: 495px"></div>
</div>
</body>
</html>
An example of it working fine for the Google Maps API version 2 is here http://www.virtualvideomap.com/
Also on http://maps.google.com You can see youtube videos inside the Info Window working in Chrome and Safari by clicking "More..." on the top right of the map, and then checking "Videos".
This is a webkit bug, but you can find a solution here: http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/ccaaee32b89e3656/c87bb19e4662bd78#c87bb19e4662bd78
Got a partial solution, use the iframe embed mode sorted the problem out to me!
Hope it helps!!
<!doctype html>
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var map;
function initialize() {
latlng = new google.maps.LatLng(33.4222685, -111.8226402)
myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),myOptions)
var point = new google.maps.LatLng(33.4222685, -111.8226402);
var marker = new google.maps.Marker({
position: point,
map: map
})
google.maps.event.addListener(marker, "click", function(){
bubble = new google.maps.InfoWindow({
content: '<iframe title="YouTube video player" class="youtube-player" type="text/html" width="480" height="390" src="http://www.youtube.com/embed/UmFjNiiVk9w?rel=0" frameborder="0"></iframe>'
})
bubble.open(map, marker);
})
}
</script>
</head>
<body onload="initialize();">
<div id="map" style="width: 984px; height: 495px"></div>
</div>
</body>
</html>
I recently solved this problem by adding the style:
iframe { -webkit-transform:translate3d(0,0,0); }
to my css file. In my case all of the dynamic content was already inside an iFrame and I was still having this problem. I saw this transform suggestion somewhere awhile ago, but only just tried it today. I tested it in Chrome and Safari on Windows 7. There is still some position lag, but it basically works fine now.

Resources