Store locator - Directions from postcode to chosen store - javascript

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:
var start_marker = new google.maps.LatLng(document.getElementById('address').value);
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.

Related

Google Maps geocode() loop to place markers

I have an array with location data with one of the items being an address - ie. "123 Main Street, San Francisco, California". I want to take that address, turn it into coordinates, then use those coordinates to plot a marker on the map. To do this, I know I need to use geocode(), so I added that part into my loop.
If I were to use latitude and longitude in my array instead of the address, I can get this to work fine. But, since I added geocode() into my loop, I can only get the first location in the array to display a marker.
I have seen some similar questions on here that suggest using callback() but I did not understand it. I've also seen a suggestion to add a delay to geocode() of 0.5 seconds which worked for the poster, but comments said it may not load all locations on slower internet speeds.
How can I fix this to show all locations in the correct way?
// Create the map with markers.
function createmap(zoomlevel, centerpos, showDot)
{
// Create the map canvas with options.
var map = new google.maps.Map(document.getElementById('map-canvas'), {
scrollwheel: false,
draggable: true,
mapTypeControl: false,
zoom: zoomlevel,
center: new google.maps.LatLng(40.577453, 2.237408), // Center the map at this location.
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
// For each location in the array...
for (i = 0; i < locations.length; i++)
{
// Get the coordintes for the address.
var geocoder = new google.maps.Geocoder();
var address = locations[i][5]; // ***This variable will output the address.***
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location_latitude = results[0].geometry.location.lat();
var location_longitude = results[0].geometry.location.lng();
// Create the map marker icon (SVG file).
var marker_icon = {
url: '//'+domain+'/__NEW__/_backend/assets/img/map-marker.svg',
anchor: new google.maps.Point(25,50),
scaledSize: new google.maps.Size(50,50)
}
// Place the marker on the map.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location_latitude, location_longitude),
map: map,
icon: marker_icon
});
}
});
}
}
This is how I am placing map markers on Google Maps:
<script type="text/javascript">
let map;
let parameters;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: #Model.Latitude , lng: #Model.Longitude },
zoom: #Model.Zoom,
});
#foreach (var asset in dbService.Assets)
{
#if (asset.State != Models.AssetState.deleted)
{
#:parameters = 'Id = #asset.Id\n' + 'Temperature = #asset.Temperature\n' + 'Moisture = #asset.Moisture\n';
#:setMarker('#asset.Latitude', '#asset.Longitude', '#asset.State');
}
}
}
function getIconByState(state) {
if (state == 'non_functional') {
return 'non-functional.png';
}
else if (state == 'under_maintenance') {
return 'under-maintenance.png';
}
else if (state == 'functional') {
return 'functional.png';
}
}
function setMarker(lat, lng, state) {
var markerjs = new google.maps.Marker({
icon: getIconByState(state),
position: new google.maps.LatLng(lat, lng),
});
markerjs.setMap(map);
let infowindow = new google.maps.InfoWindow({
content: parameters,
});
markerjs.addListener("click", () => {
infowindow.open(map, markerjs);
});
}
</script>
//this is how to use the callback
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap&libraries=&v=weekly"
defer></script>
In this code, I use the latitude and longitude to place a marker on the Map.
If you want to extract the latitude and longitude from an address, then use geocoder API in the following way:
<script type="text/javascript">
function setCoordinates() {
let address = document.getElementById('zip').value;
if (address) {
let geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('latitude').value = results[0].geometry.location.lat();
document.getElementById('longitude').value = results[0].geometry.location.lng();
}
else {
console.log('geocoding failed');
}
});
}
}
else {
alert('Please enter postal code to use this functionality');
}
}
</script>

Why is my reverse geocoding not working and displaying?

I have a nearby search map, in every open of this map page, it returns the current position, now When I get the current position by coordinates, I want to reverse geocode it into an address name, the problem is I modified my code from this source: https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/geocoding-reverse
with
<script>
function getPosition() {
navigator.geolocation.getCurrentPosition(position => {
currentLatLon = [position.coords.latitude, position.coords.longitude];
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(
document.getElementById('map'), {
center: new google.maps.LatLng(...currentLatLon),
zoom: 20
});
var geocoder = new google.maps.Geocoder();
service = new google.maps.places.PlacesService(map);
document.getElementById("curr").innerHTML=currentLatLon;
document.getElementById("address").value=currentLatLon;
geocodeLatLng(geocoder,map,infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('curr').value;
var latlngStr = input.split(',');
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
</script>
this should return the place name in the map which is like the source code I copied from above
https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/geocoding-reverse, what could be wrong in my modification? I have an error in the console when I run my modified code, error in the console
Here's my full code without the api key: https://pastebin.com/BhEqRsq0
You set the lat/lng coordinates to the <p> element's innerHTML, not to its (unsupported) value which is why it returns undefined:
document.getElementById("curr").innerHTML = currentLatLon;
So change this code:
var input = document.getElementById('curr').value;
to the following:
var input = document.getElementById('curr').innerHTML;
I just ran your web app on my end and reverse geocoding works fine after the above fix. So hope this helps!

Google direction API - How to pass Latitude and Longitude instead of Physical address

Really need some ideas on this. Been working on Google map API, which I'm using Geocoding, Reverse Geocoding and Geolocation. With this piece of code, below,I am able to use Direction API of Google map, which works perfectly.
var locations = [
{lat: 6.4261139, lng: 3.4363691}
];
var mapContainer = $('.map-container'),
map = new google.maps.Map(mapContainer[0], {
center: center,
zoom : 10
});
var markers = _(locations)
.map(function (loc) {
return new google.maps.Marker({
position: new google.maps.LatLng(loc.lat, loc.lng)
});
})
.each(function (marker) {
marker.setMap(map);
})
.value();
var mc = new MarkerClusterer(map, markers);
var directionsService = new google.maps.DirectionsService(),
directionsDisplay = new google.maps.DirectionsRenderer(),
displayRoute = function () {
directionsService.route({
origin: 'Akin Ogunlewe street VI',//6.512596400000001+','+3.3541297 Pass this in place of the address
destination: 'Falolu road Surulere',//'Falolu road Surulere',//6.4261139+','+3.4363691 Pass this in place of the address
travelMode : google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
console.log('Directions request failed due to ' + status);
}
});
};
directionsDisplay.setMap(map);
displayRoute();
Is there a way I can pass Latitude and Longitude in Origin and Destination Instead of physical address (string)?
I tried it but did not work.
I need to pass the numeric (float) value like:6.512596400000001,3.3541297 Instead of Falolu road Surulere
Any help is appreciated thanks
The documentation for the v3 API says a google.maps.LatLng or a string. For geographic locations, create and pass in a google.maps.LatLng; for addresses, pass in a string.
origin: LatLng | String | google.maps.Place,
destination: LatLng | String | google.maps.Place,
And in the reference
destination | Type: Place | Location of destination. This can be specified as either a string to be geocoded, or a LatLng, or a Place. Required.
origin | Place | Location of origin. This can be specified as either a string to be geocoded, or a LatLng, or a Place. Required.
proof of concept fiddle
code snippet:
var map;
function initialize() {
var locations = [{
lat: 6.4261139,
lng: 3.4363691
}];
var mapContainer = $('.map-container'),
map = new google.maps.Map(mapContainer[0], {
center: locations[0],
zoom: 10
});
var directionsService = new google.maps.DirectionsService(),
directionsDisplay = new google.maps.DirectionsRenderer(),
displayRoute = function() {
directionsService.route({
origin: new google.maps.LatLng(6.512596400000001, 3.3541297), // Pass this in place of the address 'Akin Ogunlewe street VI'
destination: new google.maps.LatLng(6.4261139, 3.4363691), // Pass this in place of the address 'Falolu road Surulere'
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
console.log('Directions request failed due to ' + status);
}
});
};
directionsDisplay.setMap(map);
displayRoute();
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas" class="map-container"></div>

Google Maps Apiv3 - Geocode function to get latitude longtitude not working

I modified the javascript from https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple to
var geocoder;
var postalArr = [];
postalArr.push(249586);
postalArr.push(266751);
var map;
function initialize(){
var myLatlng = new google.maps.LatLng(1.3667, 103.7500);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
if (postalArr) {
for (var i = 0; i < postalArr.length; i++ ) {
codeAddress(postalArr[i]);
}
}
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
}
function codeAddress(postal) {
geocoder.geocode( { 'postal': postal}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var markerE = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
The script goes within the for loop but doesn't run the codeAddress function.
I'm not sure why.
Two things.
(1) need to define geocoder somewhere, I put it in the initialize
function initialize(){
geocoder = new google.maps.Geocoder();
(2) there's no such thing as a postal property to feed the geocoder. Valid requests are for a latlng or an address as explained here.
So at least you must specify a country. I'm not sure what country 249586 is for, in my demo I used two California zip codes, and added ", United States" to the address.
geocoder.geocode( { 'address': postal + ", United States"},

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