I have a problem with plotting a route from my position to a certain position , I need to take my latitude and longitude of the origin variable and simply attached code to see if someone manages to solve
try to leave the values in other variables , leaving them in a marker , among other ...
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see a blank space instead of the map, this
// is probably because you have denied permission for location sharing.
var map;
function initialize() {
var pos;
var latitud;
var longitud;
var dirinicial;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
//var hola = pos;
latitud = position.coords.latitude;
longitud = position.coords.longitude;
/* var marker = new google.maps.Marker({
position: pos,
map: map,
title: 'Hello World!'
});
*/
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
// content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
var request = {
origin:'Santiago',
destination: 'Rancagua',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsDisplay.setMap(map);
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
/* // Display the distance:
document.getElementById('distance').innerHTML +=
response.routes[0].legs[0].distance.value + " meters";
// Display the duration:
document.getElementById('duration').innerHTML +=
response.routes[0].legs[0].duration.value + " seconds";
*/
directionsDisplay.setDirections(response);
}
});
}
function GetAddress(latlang) {
var latlng = new google.maps.LatLng(latitud, longitud);
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
dirinicial= results[1].formatted_address;
//alert("Location: " + results[1].formatted_address);
}
}
});
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Thanks in advance
regards from chile!
I see several errors here. First, your error management displays an infowindow at a random location {lat:60, lng:105} that's not related to the user eventual position.
Second, your route request has fixed origin and destination (Santiago and Rancagua), disregarding the user's current location at all. You should instead wait for the HTML5 geolocation API to return something to use as origin.
I've simplified your code a bit, and got this working
var map;
function initialize() {
var pos;
var latitud;
var longitud;
var dirinicial;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var generateRoute=function(origin,destination) {
var request = {
origin:origin,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsDisplay.setMap(map);
directionsService.route(request, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
};
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
var yourpositionmarker = new google.maps.Marker({position:pos, map:map});
infowindow.open(map,yourpositionmarker);
map.setCenter(pos);
generateRoute(pos, 'Rancagua');
});
} else {
// Browser doesn't support Geolocation
console.log('No geolocation API');
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Related
Currently I have encounter a problem. I used and changed sample API to draw route for two points. Point A is current location. Point B is one of the multiple markers' location. Those markers are created which I call nearby search function.
function showInfoWindow() {
var marker = this;
places.getDetails({
placeId: marker.placeResult.place_id
},
function(place, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
infoWindow.open(map, marker);
buildIWContent(place);
});
var clickLat = marker.position.lat();
var clickLon = marker.position.lng();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
var directionsService = new google.maps.DirectionsService();
showRoute(clickLat, clickLon, directionsDisplay, directionsService);
}
function showRoute(clickLat, clickLon, directionsDisplay, directionsService) {
var pointA = {
lat: currentLat,
lng: currentLon
};
var pointB = {
lat: clickLat,
lng: clickLon
};
directionsDisplay.setOptions({
suppressMarkers: true
});
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
// Set destination, origin and travel mode.
var request = {
destination: pointB,
origin: pointA,
travelMode: google.maps.TravelMode.DRIVING
};
//directionsDisplay.setMap(null);
// Pass the directions request to the directions service.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
//directionsDisplay.set('directions', null);
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
These codes could draw route for two points already. But the problem is when I click one marker call the showInfoWindow() it will draw one route, and click another one when it will call the showInfoWindow() again it will draw another route remaining the previous one route.I want to clear the previous one route. Tried all the methods online and could not find the reason.
If you only want one directions result displayed on the map at the time, only create and use one instance of the DirectionsRenderer, currently you create a new one for every result from the DirectionsService.
proof of concept fiddle
code snippet:
var geocoder;
var map;
var places;
var infoWindow = new google.maps.InfoWindow();
//Jersey City, NJ, USA
var currentLat = 40.7281575;
var currentLon = -74.0776417;
// global reference to the DirectionsRenderer
var directionsDisplay;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
places = new google.maps.places.PlacesService(map);
// initialize the global DirectionsRenderer
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
var marker1 = new google.maps.Marker({ /* New York, NY, USA */
position: {
lat: 40.7127837,
lng: -74.0059413
},
placeResult: {
place_id: "ChIJOwg_06VPwokRYv534QaPC8g"
},
map: map
});
google.maps.event.addListener(marker1, 'click', showInfoWindow);
var marker2 = new google.maps.Marker({ /* Newark, NJ, USA */
position: {
lat: 40.735657,
lng: -74.1723667
},
placeResult: {
place_id: "ChIJHQ6aMnBTwokRc-T-3CrcvOE"
},
map: map
});
google.maps.event.addListener(marker2, 'click', showInfoWindow);
var bounds = new google.maps.LatLngBounds();
bounds.extend(marker1.getPosition());
bounds.extend(marker2.getPosition());
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
function showInfoWindow() {
var marker = this;
places.getDetails({
placeId: marker.placeResult.place_id
},
function(place, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
infoWindow.open(map, marker);
buildIWContent(place);
});
var clickLat = marker.position.lat();
var clickLon = marker.position.lng();
var directionsService = new google.maps.DirectionsService();
showRoute(clickLat, clickLon, directionsDisplay, directionsService);
}
function showRoute(clickLat, clickLon, directionsDisplay, directionsService) {
var pointA = {
lat: currentLat,
lng: currentLon
};
var pointB = {
lat: clickLat,
lng: clickLon
};
directionsDisplay.setOptions({
suppressMarkers: true
});
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
// Set destination, origin and travel mode.
var request = {
destination: pointB,
origin: pointA,
travelMode: google.maps.TravelMode.DRIVING
};
//directionsDisplay.setMap(null);
// Pass the directions request to the directions service.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
//directionsDisplay.set('directions', null);
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body,
#map_canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
I have this Javascript code on Google maps with geolocation and direction and I am using it in cordova , it gives me problems because it lacks the event Deviceready.
I tried to put it , but it was not working.
You are able to add it in the right way ?
Code:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
// default location. When geolocation tracks the client, this variable is set to that location
function initialize() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//here there is marker
directionsDisplay.setMap(map);
map.setCenter(mylocation);
}
function updateRoute() {
calcRoute(mylocation);
}
function calcRoute(start) {
var start = mylocation;
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.WALKING,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
mylocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
//document.getElementById('start').value = ;
if (map) {
calcRoute(position.coords.latitude +','+ position.coords.longitude);
map.setCenter(mylocation);
//*Posizione Utente*//
var image = 'user.png'
var marker1 = new google.maps.Marker({
position: mylocation,
map: map,
title: 'ciao!',
icon: image
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow1.open(map,marker1);
});
var infowindow1 = new google.maps.InfoWindow({
content: '<img src="user.png">Sono Qui.....'
});
}
})
}
google.maps.event.addDomListener(window, 'load', initialize);
I am currently developing a "uber" like web app and am working with the google maps api.
Right now I have a home.jsp page with the following code:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Home Page</title>
<style type="text/css">
div.nav{
text-align:right;
}
div.right{
display:inline;
}
</style>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src=
"https://google-maps-utility-library-v3.googlecode.com/svn/trunk/geolocationmarker/src/geolocationmarker-compiled.js"></script>
<script language="JavaScript" type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 13
};
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function codeAddress() {
var addr = document.getElementById('destaddress').value;
geo.geocode({
'address': addr
}, function(results, status) {
console.error(status);
if (status === google.maps.GeocoderStatus.OK) {
//map.setCenter(results[0].geometery.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometery.location
});
//marker.setPosition(results[0].geometery.location);
//marker.setMap(map);
} else {
alert('Error: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function() {
if (!navigator.geolocation) return;
navigator.geolocation.getCurrentPosition(function(pos) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(pos.coords.latitude,
pos.coords.longitude);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
$("#address").text(results[0].formatted_address);
}
});
});
});
</script>
</head>
<body>
<div class="nav">
Home | Log Out
</div>
<p>Welcome eric</p>
<div id="googleMap" style="width:750px;height:500px;"></div><br>
You are currently located at
<div id="address" style="font-weight: bold;"></div><br>
Enter Destination Address:
<form>
<input id="destaddress" size="100" type="text"> <input onclick=
"codeAddress()" type="button" value="Go">
</form>
</body>
</html>
This .jsp page displays a google map located at the users current address and also displays the users current address using the api's reverse geocoder.
I am also trying to allow the user to search by address (using the regular geocoder) to place a destination marker on the map displayed on the page.
I have looked at several examples of this, but for some reason I keep getting an error message: Uncaught ReferenceError: system is not defined
According to the error console this errors point to lines codeAddress home.jsp:73 and onclick home.jsp:117.
I have searched around for a while, but I cannot find any results from a similar error.
Any ideas on how to resolve this issue?
The error is that you are using java code in your JSP without scriptlet marker. Due this in generated HTML System is interpreted as a javascript object, causing the error.
That's your error:
function codeAddress() {
var addr = document.getElementById('destaddress').value;
System.out.println(addr); // your error are here
// ...
}
If you want to show the value of addr in the browser console, use like this:
function codeAddress() {
var addr = document.getElementById('destaddress').value;
console.log(addr);
// ...
}
Even so, after that, you will see other errors. For example, geo is also undefined.
The code below should work:
var map;
var geo = new google.maps.Geocoder();
function initialize() {
var mapOptions = {
zoom: 13
};
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function codeAddress() {
var addr = document.getElementById('destaddress').value;
console.log(addr);
geo.geocode({
'address': addr
}, function(results, status) {
console.log(status);
if (status === google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Error: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I have a map that gives directions based on geolocation, however I want a marker to be on the map even before the user gets directions. I can't seem to get the marker to show up when the webpage loads. The code I am using is as follows:
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var directionDisplay, map;
function calculateRoute(from, to) {
// Center initialized to Lafayette IN
var travelMode = $('input[name="travelMode"]:checked').val();
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(40.40541,-86.89048),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var panel = document.getElementById("directionsPanel");
var marker = new google.maps.Marker({
position: new google.maps.LatLng(40.40541,-86.89048),
map: map,
title: "Beyond the Box"
});
marker.setMap(map);
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
var directionsService = new google.maps.DirectionsService();
var directionsRequest = {
origin: from,
destination: to,
travelMode: google.maps.DirectionsTravelMode[travelMode],
unitSystem: google.maps.UnitSystem.IMPERIAL
};
directionsService.route(
directionsRequest,
function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
new google.maps.DirectionsRenderer({
map: mapObject,
directions: response,
});
}
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay = new google.maps.DirectionsRenderer({
map: mapObject,
directions: response,
});
directionsDisplay.setPanel(panel);
}
else
$("#error").append("Unable to retrieve your route<br />");
}
);
}
$(document).ready(function() {
// If the browser supports the Geolocation API
if (typeof navigator.geolocation == "undefined") {
$("#error").text("Your browser doesn't support the Geolocation API");
return;
}
$("#from-link, #to-link").click(function(event) {
event.preventDefault();
var addressId = this.id.substring(0, this.id.indexOf("-"));
navigator.geolocation.getCurrentPosition(function(position) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
$("#" + addressId).val(results[0].formatted_address);
else
$("#error").append("Unable to retrieve your address<br />");
});
},
function(positionError){
$("#error").append("Error: " + positionError.message + "<br />");
},
{
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
});
});
$("#calculate-route").submit(function(event) {
event.preventDefault();
calculateRoute($("#from").val(), $("#to").val());
});
});
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<body onLoad="calculateRoute()">
<!-- Start Header -->
<?php include("header.php"); ?>
<!-- End Header -->
You didn't initialize "map" variable.
Try this.
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
marker.setMap(mapObject);
What i am trying to do is find my current location with the Geolocation API, and then add the google places, to show what is around myself. However what I have so far only returns a specific location...
<script>
var map;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
As you can see pyrmont - gives me the lat and long, but i would like to replace with this the users current location. So I can find out where they are and then give them some shops. I keep drawing a blank when I try to do this. I have done geolocation before with:
new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
however if I use this var in the lat long section I get a loverly error. Thanks for any help in advance.
Okay this did it:
<script>
var map;
function initialize() {
var mapOptions = {
};
map = new google.maps.Map(document.getElementById('contact-map'),{
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var request = {
location: pos,
radius: 500,
types: ['store']
};
var marker = new google.maps.MarkerImage('../img/layout/marker.png');
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
icon: marker,
content: 'youre here'
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>