I have a JavaScript postcode search that searches for the 3 closet stores in the UK depending on what is entered into the input. At the moment it finds the 3 stores fine.
Firstly, I want to drop a marker at the postcode entered in the input.
Secondly, when the three results show up, they are marked on the map. I want to have a link called directions that, once clicked, will show directions from the start to the chosen store.
I have tried the following code but it doesn’t work…however it does get the postcode data from the input and from the directions link and shows them in the console. Will I need to convert them into long and lat for it to work?
function calcRoute() {
var start = document.getElementById('address').value;
var end = document.getElementById('get-directions').name;
//console.log(start, end)
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);
}
});
}
I have this code for my start marker, but this doesn’t seem to work either
function initialize() {
var start_marker = new google.maps.LatLng(document.getElementById('address').value);
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: start_marker
}
marker = new google.maps.Marker({
map:map,
draggable:false,
animation: google.maps.Animation.DROP,
position: start_marker,
});
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
}
This part gets the long/lat data from the postcode,
this.geocode = function(address, callbackFunction) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var result = {};
result.latitude = results[0].geometry.location.lat();
result.longitude = results[0].geometry.location.lng();
callbackFunction(result);
//console.log(result);
//console.log("Geocoding " + geometry.location + " OK");
addMarker(map, results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
callbackFunction(null);
}
});
And the function for the addMarker is here:
function addMarker(map, location) {
console.log("Setting marker for (location: " + location + ")");
marker = new google.maps.Marker({
map : map,
animation: google.maps.Animation.DROP,
position : location
});
}
Any help would be greatly appreciated!
The constructor for a google.maps.LatLng requires two floating point numbers as arguments, not a string:
If all you have is an address, you need to use the Geocoding service to retrieve coordinates for that address if you want to display a marker on the map.