Google Maps API: Geocoder: unknown property function: - javascript

I'm currently trying to Google Geocoder API to convert an address into Lat/Lng coordinates, however, when using the example on their dev documentation(https://developers.google.com/maps/documentation/javascript/geocoding), I am running into an error of "InvalidValueError: unknown property function"
In my HTML file, I have the call to google map API and a map div, where my map should be rendered. (of course i have other stuff too, but just for the sake of getting straight to the point i will only post the relevant code)
<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap" async defer></script>
<div id="map"></div>
And in my JS file:
window.initMap = function(){
var fromLocation = new google.maps.LatLng(37.09024, -95.712891),
destLocation = new google.maps.LatLng(37.09024, -95.712891),
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.09024 , lng: -95.712891}, // center of USA
zoom: 4 // continet level
}),
directionService = new google.maps.DirectionsService(),
directionRender = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: fromLocation,
title: "Point A",
label: "From",
map:map
}),
markerB = new google.maps.Marker({
position: destLocation,
title: "Point B",
label:"Destination",
map:map
});
getLatLng("Los Angeles");
} // end of initMap
function getLatLng(address){
geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address, function(results,status){
if(status === 'OK'){
console.log(results[0].geometry.location);
}
else{
console.log("Geocoding couldn't convert string address to lat/long points");
}
}
});// end of geocoder method.
}
Any idea on how to fix the unknown property function error?
Thanks!

You have a typo in the function getLatLng:
geocoder.geocode({
address: address,
There needs to be a "}" after address: address
function getLatLng(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: address},
function(results, status) {
if (status === 'OK') {
console.log(results[0].geometry.location);
} else {
console.log("Geocoding couldn't convert string address to lat/long points");
}
}); // end of geocoder method.
}
window.initMap = function() {
var fromLocation = new google.maps.LatLng(37.09024, -95.712891),
destLocation = new google.maps.LatLng(37.09024, -95.712891),
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 37.09024,
lng: -95.712891
}, // center of USA
zoom: 4 // continet level
}),
directionService = new google.maps.DirectionsService(),
directionRender = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: fromLocation,
title: "Point A",
label: "From",
map: map
}),
markerB = new google.maps.Marker({
position: destLocation,
title: "Point B",
label: "Destination",
map: map
});
getLatLng("Los Angeles");
} // end of initMap
function getLatLng(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: address
},
function(results, status) {
if (status === 'OK') {
console.log(results[0].geometry.location);
} else {
console.log("Geocoding couldn't convert string address to lat/long points");
}
}); // end of geocoder method.
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<div id="map"></div>

Related

Google Maps Infowindow issue after Geocode adaptation

I switched my code from the lat-lang system to the geocode API in order to resolve addresses, but unfortunately, the Google Maps Infowindows don't work properly. Only a few of them are displayed, with wrong information.
Here there is my code.
<script type="text/javascript">
if(document.getElementById("{idMap}")) {
let geocoder;
let map;
let locations = [
[ "Location 1" , "Via Pavia 57, 80021" ] ,
[ "Location 2" , "Via Palermo 24, 80021" ] ,
[ "Location 3" , "Via Milano 15, 80021" ] ,
];
function initializeMap() {
geocoder = new google.maps.Geocoder();
let infowindow = new google.maps.InfoWindow();
let bounds = new google.maps.LatLngBounds();
let mapSettings = {
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false,
};
map = new google.maps.Map(document.getElementById("{idMap}"), mapSettings);
for (i = 0; i < locations.length; i++) {
codeAddress(locations[i][1], i, bounds);
}
}
function codeAddress(address, index, bounds) {
geocoder.geocode({ address: address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
let latLng = {
lat: results[0].geometry.location.lat(),
lng: results[0].geometry.location.lng(),
};
if (status == "OK") {
let marker = new google.maps.Marker({
position: latLng,
map: map,
icon: "https://maps.google.com/mapfiles/ms/icons/blue-dot.png",
});
bounds.extend(marker.position);
map.fitBounds(bounds);
map.panToBounds(bounds);
if(locations[0][index] && locations[0][index].length > 0) {
let infowindow = new google.maps.InfoWindow({
content: locations[0][index],
});
marker.addListener("click", function () {
infowindow.open(map, marker);
});
}
} else {
console.log(
"Geocode was not successful for the following reason: " + status
);
}
}
});
}
window.initMap = null;
window.initMap = initializeMap();
}
</script>
All the markers are correctly positioned, the issue is only related to the infoWindow.
I fixed the issue, passing the id from the marker to the location array, in this way it works:
let infowindow = new google.maps.InfoWindow({
content: locations[marker.id][1],
});

google map is rendered with multiple rounded tiles

map is devided into 3x3 tiles
I want to remove all the spaces and rounded corners so the map looks as if it is one full map without any divisions into tiles, maybe there is some kind of map tile atribute that I can modify to make it look like a normal map, below is my code
function initMap() {
var pointA = new google.maps.LatLng(51.7519, -1.2578),
pointB = new google.maps.LatLng(50.8429, -0.1313),
myOptions = {
zoom: 7,
center: pointA
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: pointA,
title: "point A",
label: "A",
map: map
}),
markerB = new google.maps.Marker({
position: pointB,
title: "point B",
label: "B",
map: map
});
google.maps.event.trigger(map, 'resize');
// get route from A to B
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {
directionsService.route({
origin: pointA,
destination: pointB,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
swal("не удалось загрузить карту");
}
});
}
initMap();
the tiles of the map are effected by img styling, I changed my css to bypass the map styling and it solved my issue

Set marker in the callback function where user's position is available after creating the map

I made a function that display nearest hotels in google map.my code is as follow.
var map;
function initMap() {
var latlng = new google.maps.LatLng(28.535516,77.391026);
if (navigator.geolocation) {
try {
navigator.geolocation.getCurrentPosition(function(position) {
var myLocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
setPos(myLocation);
});
} catch (err) {
var myLocation = {
lat: 25.2048,
lng: 55.2708
};
setPos(myLocation);
}
} else {
var myLocation = {
lat: 25.2048,
lng: 55.2708
};
setPos(myLocation);
}
}
function setPos(myLocation) {
map = new google.maps.Map(document.getElementById('map'), {
center: myLocation,
zoom: 10
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: myLocation,
radius: 4000,
types: ['hotels']
}, processResults);
}
function processResults(results, status, pagination) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
} else {
createMarkers(results);
}
}
function createMarkers(places) {
var bounds = new google.maps.LatLngBounds();
var placesList = document.getElementById('places');
for (var i = 0, place; place = places[i]; i++)
{
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
animation: google.maps.Animation.DROP,
position: place.geometry.location
});
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
}
html,body {
margin: 0;
padding: 0;
}
#map {
height: 500px;
margin: 10px auto;
width: 800px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuBzeYkYimIquGG5KkIcB6vFmtHMUzDFo&libraries=places&callback=initMap" async defer></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuBzeYkYimIquGG5KkIcB6vFmtHMUzDFo&libraries=places"></script>
<div id="map"></div>
Above Example Returns me nearest hotels around user location. but i wants to also display users location pointer.
So how can i show users location here.
i also try by custom adding in initMap() function to show users location marker but it OVERRIDE with Hotels icons. so when i refresh page first for microseconds user location shows and than hotels icon will override that.
here is my image with o/p of above code.
Output of Fiddle Snippet
Add the creation of the marker to the setPos function (where the geolocation results are available and the map has been create.
proof of concept fiddle
when geolocation fails:
when geolocation works, it shows my current location.
code snippet:
var map;
function error() {
console.log("error!")
var myLocation = {
lat: 25.2048,
lng: 55.2708
};
setPos(myLocation);
}
function initMap() {
var latlng = new google.maps.LatLng(28.535516, 77.391026);
if (navigator.geolocation) {
try {
navigator.geolocation.getCurrentPosition(function(position) {
var myLocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
setPos(myLocation);
}, error);
} catch (err) {
var myLocation = {
lat: 25.2048,
lng: 55.2708
};
setPos(myLocation);
}
} else {
var myLocation = {
lat: 25.2048,
lng: 55.2708
};
setPos(myLocation);
}
}
function setPos(myLocation) {
map = new google.maps.Map(document.getElementById('map'), {
center: myLocation,
zoom: 10
});
var marker = new google.maps.Marker({
position: myLocation,
map: map,
title: "My Position"
})
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: myLocation,
radius: 4000,
types: ['hotels']
}, processResults);
}
function processResults(results, status, pagination) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
} else {
createMarkers(results);
}
}
function createMarkers(places) {
var bounds = new google.maps.LatLngBounds();
var placesList = document.getElementById('places');
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
animation: google.maps.Animation.DROP,
position: place.geometry.location
});
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
}
html,
body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
#map {
height: 100%;
margin: 10px auto;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap" async defer></script>
<div id="map"></div>

How to limit gmap search autocomplete to limited country

I am developing a site where i am implementing Gmap with to and from facility. Everything is working good but right now i just wanted it's auto complete to limit to one specific country. Here is My code..
$(document).ready(function() {
initialize_direction_map();
setDestination();
$("#start").autocomplete({
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
//This bit is executed upon selection of an address
select: function(event, ui) {
$("#s_latitude").val(ui.item.latitude);
$("#s_longitude").val(ui.item.longitude);
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
map.setCenter(location);
map.setZoom(12);
var marker = new google.maps.Marker({
position: location,
map: map
});
document.getElementById('direction_box').style.display='block';
calcRoute();
}
});
$("#end").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
//This bit is executed upon selection of an address
select: function(event, ui) {
$("#e_latitude").val(ui.item.latitude);
$("#e_longitude").val(ui.item.longitude);
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
calcRoute();
$("table.adp-directions").css("width","300px");
}
});
});
function initialize_direction_map(){
//MAP
directionsDisplay = new google.maps.DirectionsRenderer();
var latlng = new google.maps.LatLng(20.5937,78.9629);
var options = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), options);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
//GEOCODER
geocoder = new google.maps.Geocoder();
}
You can use Google Maps JavaScript API Places library. The function in the Google Places JavaScript library enable your application to search for places contained within a defined area, such as the bounds of a map or around a fixed point.
Here's a sample code how to restrict by country:
function initialize() {
var options = {
types: ['(cities)'],
componentRestrictions: {country: "us"}
};
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, options);
}

How to show 2 markers on a Google Map?

How do I get multiple markers on a Google Map, using Javascript API v3? Below, when my code adds the second marker it's removing the first one.
var locations = {
"1" : {
"name": "location1",
"address": "10000 N Scottsdale Rd",
"city": "Scottsdale",
"state": "AZ",
"zipcode": "85253"
},
"2" : {
"name": "location2",
"address": "15440 N 71st Street",
"city": "Scottsdale",
"state": "AZ",
"zipcode": "85254"
}
}
var geocoder = new google.maps.Geocoder();
for (item in locations) {
var loc = locations[item].address + ", " + locations[item].city + " " +
locations[item].state + " " + locations[item].zipcode;
geocoder.geocode( { 'address': loc}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var options = {
zoom: 10,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
}
if (map) {
new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: locations[item].name
});
} else {
var map = new google.maps.Map(document.getElementById("map"), options);
new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: locations[item].name
});
}
var infowindow = new google.maps.InfoWindow({ content: "test"});
} else { // if map lookup fails, display a map of phoenix
var phoenix = new google.maps.LatLng(33.4483771,-112.07403729999999);
var options = {
zoom: 11,
center: phoenix,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
}
map = new google.maps.Map(document.getElementById("map"), options);
}
});
}
The map variable is only defined in the callback function, (e.g. function(results, status) {...}), so when the second geocoded point comes back, you are still creating a new map (for the second time), since that map is not initialized.
You should declare and initialize the map separately from the marker adding code.
loop through your marker construction from your data set. Each item in your set, create a marker as you normally would. instatiate your map only once and use the variable assigned to this in your marker creation.

Categories

Resources