Can't find lat long Brazil country - geolocation

I used navigator.geolocation.getCurrentPosition() for geo location and i got lat long. But when i try to access Brazil country lat long using this method can't give me lat long.
Suggest me how to get lat long values in Brazil country.
Code:
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script> var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
} }
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}
</script> </body> </html>

Related

how to use infowindow (google map API) to get back the ID of the selected location

I am displaying a list of locations (that i get through ViewBag for now) on a map and ask the user to choose one of them.
I have populated my infowindows with HTML code by looping through the list of locations.
now when the user clicks on one of the buttons in the infowindow ("Choose this one"), I want to update the view model (Venue) to include Venue.Id = the choosen location and submit back to the controller so update the database. how can I do such a thing ?
thanks a lot for your help.
here is my script code:
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<section class="scripts">
<script type="text/javascript">
$(document).ready(function () {
Initialize();
});
function Initialize() {
google.maps.visualRefresh = true;
var rabat = new google.maps.LatLng(34.019657, -6.831833);
var mapOptions = {
zoom: 11,
center: rabat,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var list =
#Html.Raw(Json.Encode(((IEnumerable<KayenChiMVC.Models.Venue>)ViewBag.TheVenue).Select(v => new
{
venueId = v.VenueID,
venueName = v.Name,
venueDistrict = v.District,
venueType = v.SurfaceType,
venueLat = v.Latitude,
venueLon = v.Longitude
})
));
var infowindow = new google.maps.InfoWindow();
for(var i=0; i<list.length;i++){
var pos = new google.maps.LatLng(list[i].venueLat, list[i].venueLon);
var html = "<table>" +
"<tr><td>Nom:</td>" + "<td> " + list[i].venueName +" </td> </tr>" +
"<tr><td>Quartier:</td>" + "<td> " + list[i].venueDistrict +" </td> </tr>" +
"<tr><td>Type de surface:</td>" + "<td> " + list[i].venueType +" </td> </tr>" +
"<tr><td></td><td><input type='button' value='Choisir ce terrain' onclick=''/></td></tr>";
createMarker(pos, list[i].venueName, html);
function createMarker(pos,title, html){
var marker = new google.maps.Marker({
'position': pos,
'map': map,
'title': list[i].venueName
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/red-dot.png');
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
}
}
</script>
</section>
Add a data-id attribute to your input to hold the venue id.
<input id="myButton" type="button" data-id="123" value="Choose this one" />
and get the data-id attribute in javascript
document.getElementById('myButton').onclick = function() {
console.log(this.getAttribute('data-id')); // will log '123'
};

PhoneGap - Resetting Plugins due to Page Load

I am facing an problem in phonegap while integrating native EmailComposer.
MailComposer should open up on button click, but it does not shows the mailComposer for IOS, same code for android is working,
My Code is as follow:
<html>
<head>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="emailcomposer.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", deviceready, true);
function deviceready() {
console.log("Device ready");
}.
//function to send mail using mail composer
function composeText(){
var vehiclemileage = document.getElementById('vehiclemileage').value;
var vehiclemodel = document.getElementById('vehiclemodel').value;
var message1 = document.getElementById('message_body').value;
var vechicleyear = document.getElementById("yeardropdown");
var strUser = vechicleyear.options[vechicleyear.selectedIndex].value;
var vehiclemake = document.getElementById("vehiclemake");
var makevehicle = vehiclemake.options[vehiclemake.selectedIndex].value;
var deviceName = device.platform;
var devicemodel = device.model;
if(vehiclemodel == '' || makevehicle == ''){
alert("Please Enter all the Value");
navigator.notification.alert(
'Please Enter all the Value', // message
alertDismissed, // callback
'Vehicle and Model', // title
'Ok' // buttonName
);
}
else
{
//function to check folder named "RepairMyCar" and extract picture from folder to attach it to mail
var attachPath;
var attachFile= new Array();
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getDirectory("RepairMyCar", {
create: true
},
function(directory) {
console.log("Final 63" + directory.fullPath);
attachPaths = directory.fullPath;
var attachPath=attachPaths.slice(7,attachPaths.length);
var directoryReader = directory.createReader();
directoryReader.readEntries(function(entries) {
var i;
for (i=0; i<entries.length; i++) {
console.log(entries[i].name);
attachFile[i] =attachPath + "/" + entries[i].name;
}
console.log(attachFile);
},
function (error) {
alert(error.code);
});
});
}, function(error) {
alert("can't even get the file system: " + error.code);
});
var dated, fnamed, phoned, emailed;
if(typeof(Storage)!=="undefined")
{
dated = localStorage.date;
fnamed = localStorage.fname;
phoned = localStorage.phone;
emailed= localStorage.email;
}
console.log(attachFile);
var newattachment = attachFile.toString();
//Open mail composer with all datas
setTimeout(function(){window.plugins.emailComposer.showEmailComposerWithCallback(null,
"Get an Estimate",
"Date: " + dated + '<br>' + "First Name: " + fnamed + '<br>' + "Phone Number: " + phoned + '<br>' + "Email Address: " + emailed + '<br>' + "Year of Vehicle: " + strUser + '<br>' + "Make of Vehicle: " + makevehicle + '<br>' + "Model of Vehicle: " + " " + vehiclemodel + '<br>' +
"Mileage of Vehicle: " + " " + vehiclemileage + '<br>' + message1 + '<br>' + "Sent from My:" + deviceName + devicemodel,
[sth#sth.com],
[],
[],
true,
attachFile
);},100);
//Clear LoccalStorage
localStorage.clear();
//exit the app after clicking this button
navigator.app.exitApp();
// navigator.camera.cleanup(onSuccess,fail);
// function onSuccess(){
// }
// function fail(){
// }
}
}
function onFail(message) {
alert('Failed because: ' + message);
}
/***********************************************
* Drop Down Date select script- by JavaScriptKit.com
* This notice MUST stay intact for use
* Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and more
***********************************************/
//function to load year in drodown. Default selected year : Current Year
function populatedropdown(yearfield){
var today=new Date()
var yearfield=document.getElementById(yearfield)
for (var i=0; i<31; i++)
//Select Year
var thisyear=today.getFullYear()
for (var y=0; y<25; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear-=1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
</script>
</head>
<body>
<div class="wrapper">
<h1>Get a Repair Estimate</h1>
<div class="main-content">
<p>
Please Enter the Year, Make, Model and Mileage of Your Vehicle and any other information we should know.
</p>
<form class="vehicle-detail-form">
<ul>
<li>
<label>Year of Vehicle: </label>
<form action="" name="someform">
<select id="yeardropdown">
</select>
</form>
<script type="text/javascript">
//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload=function(){
populatedropdown("yeardropdown")
}
</script>
</li>
<!-- Vehicle Year Selection -->
<li><label>Model of Vehicle:</label>
<input type="text" name="vehiclemodel" id = "vehiclemodel">
</li>
<li><label>Mileage of Vehicle:</label>
<input type="number" name="vehiclemileage" id = "vehiclemileage"></li>
<li>
<textarea name="message_body" id = 'message_body' placeholder="Add Notes here(if any)"></textarea>
</li>
</form>
<div style="clear:both;"></div>
<div class="large-button-wrapper">
<button onclick="composeText();">Get Your Estimate</button>
</div>
</div>
</div>
</body>
</html>
I have kept EmailComposer.h and EmailComposer.m in plugin folder as stated in this link
I found a workaround if you work on an iOS project. I have the same issue.
After view change in backbone router console.log stops working in Xcode you can use Safari Web Inspector on your Mac. Every console.log is visible there.

How can I create multiple Google Maps with driving directions on the same page?

Thanks for any help you can provide! I have a webpage that is supposed to display multiple Google maps with driving directions and routes. However, I can only get one of the maps to load, and this map does not show the driving directions. I'm using Ruby on Rails to create the page.
Edit 3 Based on Carl's Comments
The start and end addresses appear correctly with my "#newmaps.each do" at the bottom. However, I was getting JS errors from the this.directionsDisplay and from this.directionsService so I moved both into a function initialize(). Still getting errors in the DirectionHelper.prototype.calcRoute
The error is, "ReferenceError: google is not defined"
travelMode: google.maps.TravelMode.DRIVING
<script type='text/javascript'>
function DirectionHelper(id)
{
var rendererOptions, chicago, mapOptions;
this.directionsDisplay = null;
this.id = id;
this.map = null;
rendererOptions = {
draggable: true,
panel: document.getElementById('directions_panel' + this.id)
};
function initialize() {
this.directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
this.directionsService = new google.maps.DirectionsService();
chicago = new google.maps.LatLng(41.850033, -87.6500523);
mapOptions = {
zoom: 6,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(document.getElementById("map_canvas"+this.id), mapOptions);
this.directionsDisplay.setMap(this.map);
google.maps.event.addDomListener(window, 'load', initialize(this.map));
}
}
DirectionHelper.prototype.calcRoute = function(start, end, waypoints){
var request,
self = this;
var request = {
origin: start, // an address or LatLng
destination: end, // an address or a LatLng
optimizeWaypoints: optimize,
travelMode: google.maps.TravelMode.DRIVING
};
this.directionsService.route(request, function(response, status) {
var theRoute, summaryPanel;
if (status == google.maps.DirectionsStatus.OK) {
self.directionsDisplay.setDirections(response);
theRoute = response.routes[0];
summaryPanel = document.getElementById("directions_panel" + self.id);
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < theRoute.legs.length; i++) {
var routeSegment = i+1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += theRoute.legs[i].start_address + " to ";
summaryPanel.innerHTML += theRoute.legs[i].end_address + "<br />";
summaryPanel.innerHTML += theRoute.legs[i].distance.text + "<br />";
summaryPanel.innerHTML += theRoute.legs[i].duration.text + "<br /><br />";
}
}
if(status == google.maps.DirectionsStatus.ZERO_RESULTS){
alert("Error: One or more of your addresses was not found. If you think this is an error with our website, please contact us.");
}
if(status == google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDED){
alert("Error: You have included more than eight stops along the way. Please use only eight or fewer stops, and try again.");
}
if(status == google.maps.DirectionsStatus.INVALID_REQUEST){
alert("Error: You may be missing a starting or ending point, or you may have included two starting points or two ending points: one in the dropdown menu and one in the entry box. Please edit your map and try again.");
}
if(status == google.maps.DirectionsStatus.NOT_FOUND){
alert("Error: One or more of your addresses was not found. If you think this is an error with our website, please contact us.");
}
if(status == google.maps.DirectionsStatus.OVER_QUERY_LIMIT){
alert("We're sorry! This is an internal error with Go See Campus. Please contact us so we can resolve it.");
}
if(status == google.maps.DirectionsStatus.UNKNOWN_ERROR){
alert("Error: Something went wrong when you loaded this page. Try loading the page again. You may need to log out, clear your temporary files, and log back in.");
}
});
};
var dirHelper = null;
<% #newmaps.each do |newsavedmap| %>
dirHelper = new DirectionHelper(<%= newsavedmap.id %>);
<%= "dirHelper.calcRoute('#{newsavedmap.start}', '#{newsavedmap.end}');" %>
<% end %>
</script>
EARLIER VERSIONS
Javascript
<script type='text/javascript'>
<% for newsavedmap in #newmaps %>
$(function(){
var directionsDisplay<%= newsavedmap.id %>;
var map<%= newsavedmap.id %>;
google.maps.event.addDomListener(window, 'load', initialize(map<%= newsavedmap.id %>));
});
var directionsService<%= newsavedmap.id %> = new google.maps.DirectionsService();
function initialize() {
var rendererOptions<%= newsavedmap.id %> = {
draggable: true,
panel:document.getElementById('directions_panel<%= newsavedmap.id %>')
};
directionsDisplay<%= newsavedmap.id %> = new google.maps.DirectionsRenderer(rendererOptions<%= newsavedmap.id %>);
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map<%= newsavedmap.id %> = new google.maps.Map(document.getElementById("map_canvas<%= newsavedmap.id %>"), mapOptions);
directionsDisplay<%= newsavedmap.id %>.setMap(map<%= newsavedmap.id %>);
}
function calcRoute() {
var request<%= newsavedmap.id %> = {
origin: '<%= newsavedmap.start %>',
destination: '<%= newsavedmap.end %>',
waypoints: '<%= newsavedmap.waypoints %>',
optimizeWaypoints: optimize,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService<%= newsavedmap.id %>.route<%= newsavedmap.id %>(request<%= newsavedmap.id %>, function(response<%= newsavedmap.id %>, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay<%= newsavedmap.id %>.setDirections(response<%= newsavedmap.id %>);
var route<%= newsavedmap.id %> = response<%= newsavedmap.id %>.routes[0];
var summaryPanel<%= newsavedmap.id %> = document.getElementById("directions_panel<%= newsavedmap.id %>");
summaryPanel<%= newsavedmap.id %>.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route<%= newsavedmap.id %>.legs.length; i++) {
var routeSegment = i+1;
summaryPanel<%= newsavedmap.id %>.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel<%= newsavedmap.id %>.innerHTML += route<%= newsavedmap.id %>.legs[i].start_address + " to ";
summaryPanel<%= newsavedmap.id %>.innerHTML += route<%= newsavedmap.id %>.legs[i].end_address + "<br />";
summaryPanel<%= newsavedmap.id %>.innerHTML += route<%= newsavedmap.id %>.legs[i].distance.text + "<br />";
summaryPanel<%= newsavedmap.id %>.innerHTML += route<%= newsavedmap.id %>.legs[i].duration.text + "<br /><br />";
}
}
if(status == google.maps.DirectionsStatus.ZERO_RESULTS){
alert("Error: One or more of your addresses was not found. If you think this is an error with our website, please contact us.");
}
if(status == google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDED){
alert("Error: You have included more than eight stops along the way. Please use only eight or fewer stops, and try again.");
}
if(status == google.maps.DirectionsStatus.INVALID_REQUEST){
alert("Error: You may be missing a starting or ending point, or you may have included two starting points or two ending points: one in the dropdown menu and one in the entry box. Please edit your map and try again.");
}
if(status == google.maps.DirectionsStatus.NOT_FOUND){
alert("Error: One or more of your addresses was not found. If you think this is an error with our website, please contact us.");
}
if(status == google.maps.DirectionsStatus.OVER_QUERY_LIMIT){
alert("We're sorry! This is an internal error with Go See Campus. Please contact us so we can resolve it.");
}
if(status == google.maps.DirectionsStatus.UNKNOWN_ERROR){
alert("Error: Something went wrong when you loaded this page. Try loading the page again. You may need to log out, clear your temporary files, and log back in.");
}
});
};
<% end if #newmaps %>
</script>
HTML
<% for newsavedmap in #newmaps %>
<div class="wholemap">
<% if newsavedmap.name != nil and newsavedmap.name != '' %>
<h4><%= newsavedmap.name %></h4>
<% else %>
<h4>Untitled Map</h4>
<% end %>
<a class="directions" href="#">Show Driving Directions</a>
<div class="clear"></div>
<div class="map" id="map_canvas<%= newsavedmap.id %>"></div>
<div class="route" id="directions_panel<%= newsavedmap.id %>"></div>
<div class="clear"></div>
<a id="print<%= newsavedmap.id %>" target="_blank" class="printmap">Print this map</a>
<div class="clear"></div>
</div>
<% end %>
Sample JS results
$(function(){
var directionsDisplay6;
var map6;
google.maps.event.addDomListener(window, 'load', initialize(map6));
});
var directionsService6 = new google.maps.DirectionsService();
function initialize() {
var rendererOptions6 = {
draggable: true,
panel:document.getElementById('directions_panel6')
};
directionsDisplay6 = new google.maps.DirectionsRenderer(rendererOptions6);
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map6 = new google.maps.Map(document.getElementById("map_canvas6"), mapOptions);
directionsDisplay6.setMap(map6);
}
function calcRoute() {
var request6 = {
origin: '2750 Pleasant Hill Rd Duluth, GA 30096',
destination: '500 Lee Drive, Baton Rouge, Louisiana 70808',
waypoints: '737 Denham Progress Rd Buckatunna, MS 39322',
optimizeWaypoints: optimize,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService6.route6(request6, function(response6, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay6.setDirections(response6);
var route6 = response6.routes[0];
var summaryPanel6 = document.getElementById("directions_panel6");
summaryPanel6.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route6.legs.length; i++) {
var routeSegment = i+1;
summaryPanel6.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel6.innerHTML += route6.legs[i].start_address + " to ";
summaryPanel6.innerHTML += route6.legs[i].end_address + "<br />";
summaryPanel6.innerHTML += route6.legs[i].distance.text + "<br />";
summaryPanel6.innerHTML += route6.legs[i].duration.text + "<br /><br />";
}
}
if(status == google.maps.DirectionsStatus.ZERO_RESULTS){
alert("Error: One or more of your addresses was not found. If you think this is an error with our website, please contact us.");
}
if(status == google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDED){
alert("Error: You have included more than eight stops along the way. Please use only eight or fewer stops, and try again.");
}
if(status == google.maps.DirectionsStatus.INVALID_REQUEST){
alert("Error: You may be missing a starting or ending point, or you may have included two starting points or two ending points: one in the dropdown menu and one in the entry box. Please edit your map and try again.");
}
if(status == google.maps.DirectionsStatus.NOT_FOUND){
alert("Error: One or more of your addresses was not found. If you think this is an error with our website, please contact us.");
}
if(status == google.maps.DirectionsStatus.OVER_QUERY_LIMIT){
alert("We're sorry! This is an internal error with Go See Campus. Please contact us so we can resolve it.");
}
if(status == google.maps.DirectionsStatus.UNKNOWN_ERROR){
alert("Error: Something went wrong when you loaded this page. Try loading the page again. You may need to log out, clear your temporary files, and log back in.");
}
});
};
$(function(){
var directionsDisplay7;
var map7;
google.maps.event.addDomListener(window, 'load', initialize(map7));
});
var directionsService7 = new google.maps.DirectionsService();
function initialize() {
var rendererOptions7 = {
draggable: true,
panel:document.getElementById('directions_panel7')
};
directionsDisplay7 = new google.maps.DirectionsRenderer(rendererOptions7);
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map7 = new google.maps.Map(document.getElementById("map_canvas7"), mapOptions);
directionsDisplay7.setMap(map7);
}
function calcRoute() {
var request7 = {
origin: '1600 Pennsylvania Avenue, Washington, DC 20500',
destination: '103 Federal St Pittsburgh, PA 15212',
waypoints: '50 Summit Ave Hagerstown, MD 21740',
optimizeWaypoints: optimize,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService7.route7(request7, function(response7, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay7.setDirections(response7);
var route7 = response7.routes[0];
var summaryPanel7 = document.getElementById("directions_panel7");
summaryPanel7.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route7.legs.length; i++) {
var routeSegment = i+1;
summaryPanel7.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel7.innerHTML += route7.legs[i].start_address + " to ";
summaryPanel7.innerHTML += route7.legs[i].end_address + "<br />";
summaryPanel7.innerHTML += route7.legs[i].distance.text + "<br />";
summaryPanel7.innerHTML += route7.legs[i].duration.text + "<br /><br />";
}
}
if(status == google.maps.DirectionsStatus.ZERO_RESULTS){
alert("Error: One or more of your addresses was not found. If you think this is an error with our website, please contact us.");
}
if(status == google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDED){
alert("Error: You have included more than eight stops along the way. Please use only eight or fewer stops, and try again.");
}
if(status == google.maps.DirectionsStatus.INVALID_REQUEST){
alert("Error: You may be missing a starting or ending point, or you may have included two starting points or two ending points: one in the dropdown menu and one in the entry box. Please edit your map and try again.");
}
if(status == google.maps.DirectionsStatus.NOT_FOUND){
alert("Error: One or more of your addresses was not found. If you think this is an error with our website, please contact us.");
}
if(status == google.maps.DirectionsStatus.OVER_QUERY_LIMIT){
alert("We're sorry! This is an internal error with Go See Campus. Please contact us so we can resolve it.");
}
if(status == google.maps.DirectionsStatus.UNKNOWN_ERROR){
alert("Error: Something went wrong when you loaded this page. Try loading the page again. You may need to log out, clear your temporary files, and log back in.");
}
});
};
EDIT 1
Thanks to Carl for the attempt. The immediate solution didn't work, but maybe tweaking will help. The first thing I did was alter the Ruby code to fit my setup:
<script type="text/javascript">
var dirHelper = null;
<% #newmaps.each do |newsavedmap| %>
dirHelper = new DirectionHelper(newsavedmap.id);
dirHelper.calcRoute(newsavedmap.start, newsavedmap.end, newsavedmap.waypoints);
<% end %>
</script>
My immediate error in the console: DirectionHelper is not defined. I solved this by combining the Ruby javascript above with the Javascript for Google Maps.
Next error: newsavedmap is not defined. I tried solving this by replacing newsavedmap with <%= newsavedmap.WHATEVER %> and enclosing start, end, and waypoints within quotes. However, this just resulted in another error (a is null: somehow related to my Google Ads javascript, which should work just fine.) What should I do next? Is there a different approach I should take?
Edit 2
I've tried Carl's latest solution (thanks!) but ran into more errors. Here's my setup: I used his function DirectionHelper code and everything else in the top block exactly as-is. Then, in a separate tag specific to my "newmaps" view, I used the bottom Ruby code. It looks like this:
<script type="text/javascript">
var dirHelper = null;
<% #newmaps.each do |newsavedmap| %>
dirHelper = new DirectionHelper(newsavedmap.id);
<%= "dirHelper.calcRoute('#{newsavedmap.start}', '#{newsavedmap.end}', '#{'5 Main Street Charlestown MA'}');" %>
<% end %>
</script>
Notice that I used a constant for my waypoints since they were giving me a bunch of errors, which I wanted to separate from the javascript problems.
Now, I'm just giving a javascript error: newsavedmap is not defined. Any ideas?
2013.08.15 Alright, updating my answer with a full-example of all js, html, css. You can fill in the ruby yourself, which will be trivial.
Code is also on github, here.
HTML page:
<!doctype html>
<html>
<head>
<title>multi directions</title>
<link rel="stylesheet" href="site.css" type="text/css"/>
</head>
<body>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
CSS
.map{
width:500px;
height:300px;
border: solid 1px #000;
margin-bottom:10px;
}
.directions{
width:500px;
border: dashed 1px #000;
margin-bottom: 10px;
}
JS
function DirectionHelper(id)
{
var rendererOptions, chicago, mapOptions;
this.directionsDisplay = null;
this.id = id;
this.map = null;
this.directionsService = new google.maps.DirectionsService();
var startElement = document.createElement('input');
startElement.id = 'start_'+id;
startElement.value = 'The Loop';
document.body.appendChild(startElement);
var endElement = document.createElement('input');
endElement.id = 'end_'+id;
endElement.value = 'Grant Park';
document.body.appendChild(endElement);
var mapElement = document.createElement('div');
mapElement.id = "map_" + id;
mapElement.className = 'map';
document.body.appendChild(mapElement);
var directionsPanelElement = document.createElement('div');
directionsPanelElement.id = 'directions_panel'+id;
directionsPanelElement.className='directions';
document.body.appendChild(directionsPanelElement);
rendererOptions = {
draggable: true,
panel: document.getElementById('directions_panel' + this.id)
};
this.directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
chicago = new google.maps.LatLng(41.850033, -87.6500523);
mapOptions = {
zoom: 6,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(document.getElementById("map_"+this.id), mapOptions);
this.directionsDisplay.setMap(this.map);
}
DirectionHelper.prototype.calcRoute = function(start, end, waypoints){
var request,
self = this;
request = {
origin: start, // an address or LatLng
destination: end, // an address or a LatLng
travelMode: google.maps.TravelMode.DRIVING
};
console.log(request)
this.directionsService.route(request,function(r,s){ console.log('shit') })
this.directionsService.route(request, function(response, status) {
var theRoute, summaryPanel;
if (status == google.maps.DirectionsStatus.OK) {
self.directionsDisplay.setDirections(response);
theRoute = response.routes[0];
summaryPanel = document.getElementById("directions_panel" + self.id);
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < theRoute.legs.length; i++) {
var routeSegment = i+1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += theRoute.legs[i].start_address + " to ";
summaryPanel.innerHTML += theRoute.legs[i].end_address + "<br />";
summaryPanel.innerHTML += theRoute.legs[i].distance.text + "<br />";
summaryPanel.innerHTML += theRoute.legs[i].duration.text + "<br /><br />";
}
}
if(status == google.maps.DirectionsStatus.ZERO_RESULTS){
alert("Error: One or more of your addresses was not found. If you think this is an error with our website, please contact us.");
}
if(status == google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDED){
alert("Error: You have included more than eight stops along the way. Please use only eight or fewer stops, and try again.");
}
if(status == google.maps.DirectionsStatus.INVALID_REQUEST){
alert("Error: You may be missing a starting or ending point, or you may have included two starting points or two ending points: one in the dropdown menu and one in the entry box. Please edit your map and try again.");
}
if(status == google.maps.DirectionsStatus.NOT_FOUND){
alert("Error: One or more of your addresses was not found. If you think this is an error with our website, please contact us.");
}
if(status == google.maps.DirectionsStatus.OVER_QUERY_LIMIT){
alert("We're sorry! This is an internal error with Go See Campus. Please contact us so we can resolve it.");
}
if(status == google.maps.DirectionsStatus.UNKNOWN_ERROR){
alert("Error: Something went wrong when you loaded this page. Try loading the page again. You may need to log out, clear your temporary files, and log back in.");
}
});
};
function initialize() {
var dirHelper = null;
for(var i=1; i<6; i++){
dirHelper = new DirectionHelper(i);
dirHelper.calcRoute(document.getElementById('start_'+i).value, document.getElementById('end_'+i).value);
}
}
google.maps.event.addDomListener(window, 'load', initialize);

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

displaying google maps with html5 geolocation in mvc3?

im trying to display google maps using html5 geolocation, the code is working fine is jsfiddle but in my mvc application, the map is not being displayed..posting the code below..
this is the link
http://jsfiddle.net/PhzsR/62/
#{
ViewBag.Title = "Home Page";
}
<h2>#ViewBag.Message</h2>
<div id="results"></div>
<div id="map"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var $message_area = jQuery('#results');
jQuery(document).ready(function () {
$message_area.html('<i>Locating you...</i> ');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function foundLocation(position) {
$message_area.children().remove();
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
var map;
var centerPosition = new google.maps.LatLng(latitude, longitude);
var options = {
zoom: 12,
center: centerPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map')[0], options);
var marker = new google.maps.Marker({
position: centerPosition,
map: map,
icon: 'http://google-maps-icons.googlecode.com/files/sailboat-tourism.png'
});
var circle = new google.maps.Circle({
center: centerPosition,
radius: accuracy,
map: map,
fillColor: '#0000FF',
fillOpacity: 0.5,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
map.fitBounds(circle.getBounds());
$message_area.append('Your latitude: ' + latitude + ' and longitude: ' + longitude + ' and accuracy: ' + accuracy + ':')
}, function (error) {
switch (error.code) {
case error.TIMEOUT:
$message_area.append('Timeout error while finding your location');
break;
case error.POSITION_UNAVAILABLE:
$message_area.append('Position unavailable error while finding your location');
break;
case error.PERMISSION_DENIED:
$message_area.append('Permission denied error while finding your location');
break;
case error.UNKNOWN_ERROR:
$message_area.append('Unknown error while finding your location');
break;
}
});
}
});
</script>
do i need to add any reference for displaying google maps?
If you look at the 'manage resources' tab on your fiddle, you've got a reference to Google Maps API which isn't in your code above, make sure you add
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

Resources