How to limit gmap search autocomplete to limited country - javascript

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

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 Maps API: Geocoder: unknown property function:

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>

Trying to parse external json file to create markers in google maps api

I am using JavaScript and a external JSON file.
Here is my JSON file. It is in the same folder as my js file. I called the JSON file csus_locations.JSON
{
"locations": [
{
"latitude": 38.558961,
"longitude": -121.423011,
"name": "AIRC",
"title": "THIS IS WHERE STUFF GETS DONE!"
},
{
"latitude": 38.562605,
"longitude": -121.419683,
"name": "GUY WEST",
"title": "PRESIDENT?"
},
{
"latitude": 38.556652,
"longitude": -121.423842,
"name": "well",
"title": "WORKOUT"
},
{
"latitude": 38.555465,
"longitude": -121.422551,
"name": "Hornetsatdium",
"title": "FOOTBAL!"
}
]}
I Know that this is legal json code because i tested to verify it. But can i remove "locations": and remove the brackets to make it simpler to parse into google maps?
I am trying to parse the json file using $http.get but my i am note sure if i wrote the code correctly
angular.module('app.controllers', ['ionic'])
.controller('mapCtrl', function ($scope, $ionicSideMenuDelegate, $ionicLoading, $compile, $ionicPopup, $http) {
$ionicSideMenuDelegate.canDragContent(false);
var myLatlng = new google.maps.LatLng(38.5602, -121.4241);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Sac State'
});
//i want to get parse with $http.get but i am not sure if i wrote this code correctly
$http.get('csus_locations.json').success(function(res){
console.log("success!");
$scope.locations = res.locations;
//window.alert("The app is reading the Json file!"); this was a test to see if the get function was working
var latLng_csus = new google.maps.LatLng(value.latitude, value.longitude);
var marker = new google.maps.Marker({
position: latLng_csus,
title: value.name
});
});
/* this was my first attempt to create markers
console.log(jsonCSUS);
angular.forEach(jsonCSUS, function(value, key){
var latLng_csus = new google.maps.LatLng(value.latitude, value.longitude);
var marker = new google.maps.Marker({
position: latLng_csus,
title: value.name
});
marker.setMap(map);
});*/
var onSuccess = function (position) {
//Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
$scope.map = map;
//$scope.map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.watchPosition(onSuccess, onError, {
maximumAge: 3000,
timeout: 5000,
enableHighAccuracy: true
});
});
The provided JSON file, indeed is a valid one, so you could initialize markers like this:
$http.get('csus_locations.json').success(function (data) {
$scope.locations = data.locations;
$scope.locations.forEach(function(item){
var latLng = new google.maps.LatLng(item.latitude, item.longitude);
var marker = new google.maps.Marker({
position: latLng,
title: item.name,
map: map
});
});
});
Working example
angular.module('mapApp', ['ionic'])
.controller('mapCtrl', function ($scope, $http) {
var mapOptions = {
center: new google.maps.LatLng(38.5602, -121.4241),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
$http.get('https://gist.githubusercontent.com/vgrem/c7ec78e7078c2c9ed1c3/raw/959e9d8b8e60544fcc169ea890e84a2624ed8bbb/csus_locations.json').success(function (data) {
$scope.locations = data.locations;
$scope.locations.forEach(function(item){
var latLng = new google.maps.LatLng(item.latitude, item.longitude);
var marker = new google.maps.Marker({
position: latLng,
title: item.name,
map: map
});
});
});
});
#map-canvas {
width: 800px;
height: 600px;
}
<link href="http://code.ionicframework.com/1.1.1/css/ionic.css" rel="stylesheet">
<script src="http://code.ionicframework.com/1.1.1/js/ionic.bundle.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=&v=3.0&sensor=true"></script>
<div ng-app="mapApp" ng-controller="mapCtrl">
<div id="map-canvas"></div>
</div>

Gmaps maps showing listings by Yellow pages

I have created the map using Gmaps.js and passed the location and near by places to it but its showing listings by yellowpages.ca whenever I click a place following picture explains the problem. I am new in Google maps api.
var map;
var loc;
$(document).ready(function(){
map = new GMaps({
el: '#map',
lat: -12.043333,
lng: -77.028333,
zoom:15,
});
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status){
if(status=='OK'){
var latlng = results[0].geometry.location;
lat=latlng.lat();
lng=latlng.lng();
map.setCenter(latlng.lat(), latlng.lng());
map.addMarker({
lat: latlng.lat(),
lng: latlng.lng(),
icon:$('#mainPin').val().trim(),
});
loc=new google.maps.LatLng(latlng.lat(),latlng.lng());
}}});
});
function showplaces(place,urll){
map.removeMarkers();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status){
if(status=='OK'){
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
map.addMarker({
lat: latlng.lat(),
lng: latlng.lng(),
icon:$('#mainPin').val().trim(),
});
map.addLayer('places', {
location : loc,
radius : 500,
types : [place],
search: function (results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
map.addMarker({
lat: place.geometry.location.lat(),
lng: place.geometry.location.lng(),
title : place.name,
icon:urll,
});
}
}
}
});
}
}
});
if(place=='shopping_mall')
{
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status){
if(status=='OK'){
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
map.addMarker({
lat: latlng.lat(),
lng: latlng.lng(),
icon:$('#mainPin').val().trim(),
});
map.addLayer('places', {
location : loc,
radius : 500,
types : ['shoe_store','store','department_store'],
search: function (results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
map.addMarker({
lat: place.geometry.location.lat(),
lng: place.geometry.location.lng(),
title : place.name,
icon:urll,
});
}
}
}
});
}
}
});
}
else if(place=='movie_theater')
{
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status){
if(status=='OK'){
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
map.addMarker({
lat: latlng.lat(),
lng: latlng.lng(),
icon:$('#mainPin').val().trim(),
});
map.addLayer('places', {
location :loc,
radius : 500,
types : ['movie_theater','zoo','stadium','night_club'],
search: function (results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
map.addMarker({
lat: place.geometry.location.lat(),
lng: place.geometry.location.lng(),
title : place.name,
icon:urll,
});
}
}
}
});
}
}
});
}
}
What you see there are the attributions, it's required to show them.
Of course it's not required to show them multiple times.
The issue is(you may call it bug, I would call it a bad implementation ... heaven knows why so many people use these 3rd-party maps-libraries which only introduce bugs instead of useful features).
The "bug": each time you call map.addLayer('places') a new instance of google.maps.places.PlacesService will be created. Each instance will print separate attributions.
Gmaps.js doesn't have options to:
define where the attributions will be placed
use a single instance of the placesService
My suggestion would be to give up this "library" .
When you can't do without it check at the begin of showplaces if there is an object map.singleLayers.places . When it does it is the placesService-instance. Use this instance for a nearbySearch instead of using map.addLayer('places') .

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