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);
Related
I have an application which displays postcodes from a database, when a button is clicked the postcodes are geocoded and displayed as markers on a Google map in a pop up window. I'm trying to show the driving route between the two markers on the map. I have saved the geocoded values into HTML span tags and I'm trying to use these values as the origin and destination for the route. Everything works apart from the route showing between the markers which shows an error message 'Directions request failed due to NOT_FOUND'.
Any idea how I can get the route to show up?
$(document).ready(function () {
$(".openMap").click(function () {
var directionsService = new google.maps.DirectionsService;
var mapLocation = $(this).prev().prev().prev().text();
var secondMarker = $(this).prev().prev().text();
window.markers = [];
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: mapLocation }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = { center: results[0].geometry.location, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP };
map = new google.maps.Map(document.getElementById('map'), mapOptions);
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
directionsDisplay.setMap(map);
var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: "Departure Location" });
markers.push(marker);
$('#route1').text(results[0].geometry.location);
}
});
var geocoder2 = new google.maps.Geocoder();
geocoder.geocode({ address: secondMarker }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker2 = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: "Destination Location" });
markers.push(marker2);
$('#route2').text(results[0].geometry.location);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
});
directionsService.route({
origin: $('#route1').text(),
destination: $('#route2').text(),
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
$("#map").dialog({ title: "Lift Location ", height: 500, width: 500, modal: true });
});
});
route1 and route2 are empty. The API doesn't know how to create a route from "" to "".
Once I fix that (to use post1 and post2 which contain the postcodes), I get a javascript error: Uncaught ReferenceError: directionsDisplay is not defined.
Fixing that shows me a route.
proof of concept fiddle
code snippet:
$(document).ready(function() {
var directionsDisplay;
$(".openMap").click(function() {
var directionsService = new google.maps.DirectionsService;
var mapLocation = $(this).prev().prev().prev().text();
var secondMarker = $(this).prev().prev().text();
window.markers = [];
var geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
geocoder.geocode({
address: mapLocation
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
directionsDisplay.setMap(map);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: "Departure Location"
});
markers.push(marker);
$('#route1').text(results[0].geometry.location);
}
});
var geocoder2 = new google.maps.Geocoder();
geocoder.geocode({
address: secondMarker
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker2 = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: "Destination Location"
});
markers.push(marker2);
$('#route2').text(results[0].geometry.location);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
});
console.log("post1:" + $('.post1').text());
console.log("post2:" + $('.post2').text());
directionsService.route({
origin: $('.post1').text(),
destination: $('.post2').text(),
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
if (!directionsDisplay || !directionsDisplay.getMap || (directionsDisplay.getMap() == null)) {
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
directionsDisplay.setMap(map);
}
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
$("#map").dialog({
title: "Lift Location ",
height: 500,
width: 500,
modal: true
});
$(".selector").dialog({
resizeStop: function(event, ui) {
google.maps.event.trigger(map, 'resize');
}
});
$(".selector").dialog({
open: function(event, ui) {
google.maps.event.trigger(map, 'resize');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maps.google.com/maps/api/js"></script>
<div id="map" style="display: none;">
</div>
<span class='post1'>G1 3SL</span>
<span class='post2'>G1 2AF</span>
<br/>
<button class='openMap'>View On Map</button>
<br/>
<span id="route1"></span>
<span id="route2"></span>
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 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);
Kindly check this map view: http://gmaps-samples-v3.googlecode.com/svn/trunk/map_language/map_lang.html
If you click on A or B, it will show location name in default marker. I wish to show some custom texts here. How can I do that?
My JavaScript code for this is:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var oldDirections = [];
var currentDirections = null;
//getting latitude and longitude from address
var latitude;
var longitude;
var geocoder = new google.maps.Geocoder();
var address = "Downtown Berkeley";
geocoder.geocode( { "address": address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
// do something with the geocoded result
//
latitude = results[0].geometry.location.lat()
longitude = results[0].geometry.location.lng()
alert(latitude )
}
});
//map initialize
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(-33.879,151.235),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//adding marker
var marker = new google.maps.Marker
(
{
position: new google.maps.LatLng(latitude , longitude),
map: map,
title: "Click me"
}
);
var infowindow = new google.maps.InfoWindow({
content: "Location info:<br/>Country Name:<br/>LatLng:"
});
google.maps.event.addListener(marker, "click", function () {
// Calling the open method of the infoWindow
infowindow.open(map, marker);
});
directionsDisplay = new google.maps.DirectionsRenderer({
"map": map,
"preserveViewport": true,
"draggable": true
});
directionsDisplay.setPanel(document.getElementById("directions_panel"));
google.maps.event.addListener(directionsDisplay, "directions_changed",
function() {
if (currentDirections) {
oldDirections.push(currentDirections);
}
currentDirections = directionsDisplay.getDirections();
});
calcRoute();
}
function calcRoute() {
var start = "El Cerrito del Norte";
var end = "Downtown Berkeley";
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
You set that content in the createInfoWindow() method.
I'm trying to accomplish the following with the Google Maps API:
Display to_address as a marker on the map
Get users location
Generate and display directions based on the information given by gps/user input
I have gotten the last two to work just fine. The problem I am having now is showing the to_address as a marker on the map if the location is not provided.
This is the code I am using. Keep in mind the last 2 steps work as expected. I know that I can accomplish this using latlng but that is not an option for me. I need to provide it an address.
var geocoder;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var to_pos;
var to_address = '11161 84th ave delta bc';
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': to_address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
to_pos = results[0].geometry.location;
}
});
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: to_pos
};
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions'));
var control = document.getElementById('d_options');
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.Marker({
position: pos,
map: map,
title: "You"
});
map.setCenter(pos);
$('#from').val(pos);
$('#d_options').trigger('collapse');
calcRoute();
}, function () {
handleNoGeolocation(true);
});
}
}
function calcRoute() {
var start = document.getElementById('from').value;
var end = to_address;
$('#results').show();
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
geocoding uses an asynchronous request. You must create the marker inside the callback of geocode()
geocoder.geocode({
'address': to_address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var to_pos = results[0].geometry.location;
new google.maps.Marker({
position: new google.maps.LatLng(to_pos.lat(),to_pos.lng()),
map: map,
title: "Destination"
});
}
});