Javascript/jQuery Google Maps routes not found - javascript

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>

Related

Simple Geocoding Map in JQuery

How do I make a simple map in Jquery that plots only one location. Here is the code I have now. this plots an array of locations, but I just need a simple map that will plot one point in Lng,Lat format. I am using the google geocoder for this.
var geocoder;
var map;
var markersArray = [];
var bounds;
var infowindow = new google.maps.InfoWindow({
content: ''
});
function initialize() {
geocoder = new google.maps.Geocoder();
bounds = new google.maps.LatLngBounds();
var myOptions = {
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder.geocode({
'address': '5th Avenus New Yort'
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
bounds.extend(results[0].geometry.location);
markersArray.push(marker);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
plotMarkers();
}
var locationsArray = [
['Google Official', '1600 Amphitheatre Parkway, Mountain View, USA'],
['Google 1', '112 S. Main St., Ann Arbor, USA'],
['Google 2', '10 10th Street NE, Suite 600 USA']
];
function plotMarkers() {
var i;
for (i = 0; i < locationsArray.length; i++) {
codeAddresses(locationsArray[i]);
}
}
function codeAddresses(address) {
geocoder.geocode({
'address': address[1]
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(address[0]);
infowindow.open(map, this);
});
bounds.extend(results[0].geometry.location);
markersArray.push(marker);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
map.fitBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I then call this in my file with:
<body>
<div id="map_canvas" style="width: 100%; height: 700px;"></div>
</body>
</html>
I need the new map to plot one lat and lng point along with posting the listing the location in the textbook as above. I can not figure out how to do this without an array.
It seems like you're using an example that shows multiple markers.
I haven't tested it, but I think this JavaScript is close:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
geocoder.geocode( { 'address': '5th Avenue New York' }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Review this for more information: https://developers.google.com/maps/documentation/javascript/geocoding

Google Maps Geocode not working (no markers)

I have a webpage to find latitude, longitude, and get a marker for that position. I use Google Maps.
My webpage get 2 addresses from user input, address 1 and address 2, and calls codeAddress()
<div id="panel">
<input id="address1" type="textbox" value="">
<input id="address2" type="textbox" value="">
<input type="button" value="find!" onclick="codeAddress()">
</div>
This is my JavaScript code:
var map;
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
function initialize() {
var latlng = new google.maps.LatLng(-7.275920, 112.791871);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var gc = google.maps.Geocoder();
gc.geocode({
'address': address1
}, function (res1, status) {
if (status == google.maps.GeocoderStatus.OK) {
gc.geocode({
'address': address2
}, function (res2, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: res1[0].geometry.location,
map: map
});
new google.maps.Marker({
position: res2[0].geometry.location,
map: map
});
}
});
}
});
}
When I click the button find, I didn’t get the markers. Can any body help me?
Modify the codeAddress function like this:
function codeAddress() {
var gc = new google.maps.Geocoder(); // notice new keyword
initialize(); // Calling initialize. If you skip it, maps aren't loading
gc.geocode({
'address': address1
}, function(res1, status) {
if (status == google.maps.GeocoderStatus.OK) {
gc.geocode({
'address': address2
}, function(res2, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: res1[0].geometry.location,
map: map
});
new google.maps.Marker({
position: res2[0].geometry.location,
map: map
});
}
});
}
});
Make sure both of the inputs have some value to test it.
Demo: http://jsfiddle.net/lotusgodkk/GCu2D/213/
update the address variables from the form when the function runs
function codeAddress() {
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
check for status != OK
} else alert("Geocode failed of " + address1 + ", status=" + status);
use "new" before the google maps Geocoder constructor
var gc = new google.maps.Geocoder();
remove existing markers before displaying new ones so the markers don't accumulate on the map
if (marker1 && marker1.setMap) marker1.setMap(null);
complete code:
var map = null;
var marker1 = null;
var marker2 = null;
var gc = new google.maps.Geocoder();
function initialize() {
var latlng = new google.maps.LatLng(-7.275920, 112.791871);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress();
}
function codeAddress() {
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
gc.geocode({
'address': address1
}, function (res1, status) {
if (status == google.maps.GeocoderStatus.OK) {
gc.geocode({
'address': address2
}, function (res2, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (marker1 && marker1.setMap) marker1.setMap(null);
marker1 = new google.maps.Marker({
position: res1[0].geometry.location,
map: map
});
if (marker2 && marker2.setMap) marker2.setMap(null);
marker2 = new google.maps.Marker({
position: res2[0].geometry.location,
map: map
});
} else alert("Geocode failed of " + address2 + ", status=" + status);
});
} else alert("Geocode failed of " + address1 + ", status=" + status);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
working fiddle

Marker not showing up in Google Maps api

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);

How to edit default marker in google maps

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.

Issue with Google Maps API v3

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"
});
}
});

Categories

Resources