Radius ignored google maps API - javascript

I would like to see points of interest within recover from a slider but I feel that the property radius is not taken into account.
When I try to change the value , I see the change, but it is not a good result.
Radius is in meters ?
Can you help me?
thank you in advance
var radius = 50;
$(document).ready(function(){
$('#range-input').on('change', function(evt, range) {
radius = $(this).val();
$('#range-output').val($(this).val() + "m");
});
});
var infowindow;
var latU;
var lngU;
var distance;
var motCle;
function initMap() {
var mapOptions = {
zoom:12,
scaleControl: true,
streetViewControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_CENTER
},
mapTypeId: google.maps.MapTypeId.ROADMAP
}
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(successCallback,
null,
{enableHighAccuracy:true});
else
alert("Votre navigateur ne prend pas en compte la géolocalisation, activez la localisation et réessayer");
function successCallback(position){
var distance = radius+'m';
var motCle = $('#motCle').val;
latU = position.coords.latitude ;
lngU = position.coords.longitude;
map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
var myLatLng = new google.maps.LatLng(latU, lngU);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
map: map,
name: 'Vous êtes ici',
title: 'Vous êtes ici'
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(marker.name);
infowindow.open(map, this);
});
var requestNearby = {
location: myLatLng, //Paramètre de l'endroit ou se trouve la personne
radius: distance,
types: ['shopping_mall', 'grocery_or_supermarket'],
openNow: true
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(requestNearby, callbackNearby);
function callbackNearby(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
$('#searchform').submit(function(e){
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
//alert('sa marche !');
e.preventDefault();
var myLatLng;
console.log(radius);
$.ajax({
method : $(this).attr('method'),
url : $(this).attr('action'),
data : $(this).serialize(),
dataType: 'json'
}).done(function(data){
if(data.success){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var latU = position.coords.latitude;
var lngU = position.coords.longitude;
myLatLng = new google.maps.LatLng(latU, lngU);
console.log(myLatLng);
serviceSearch = new google.maps.places.PlacesService(map);
var requestText = {
location: myLatLng,
radius: radius,
query: data['message'],
openNow: true
};
serviceSearch.textSearch(requestText, callbackText);
function callbackText(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
});
}
} else {
alert('sa ne fonctionne pas correctement!');
}
});
return false;
});
<div class="row">
<div class="col-xs-6">
<div class="range">
<input type="range" id="range-input" name="range" min="1000" max="20000" value="1000">
<output id="range-output">1000m</output>
</div>
</div>
</div>
</div>

From the documentation the radius needs to be a Number which is the distance in meters; this var distance = radius+'m'; makes it a string.
radius | Type: number
The distance from the given location within which to search for Places, in meters. The maximum allowed value is 50 000.

Related

Google Maps API infowindows returns same content

I have the old infowindows in a loop problem where the content for the last loop is showing in all infowindows. Yes I know there are several questions about this already on Stack Overflow but none of them seem to work for me.
<script>
var map;
var myMarker = [];
var myData = [];
function initialize() {
var Nazareth = { lat: -29.847073, lng: 30.853513 };
var myCenter = new google.maps.LatLng(-29.847073, 30.853513);
var mapOptions = {
center: Nazareth,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
SetMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);
var infoWindow = new google.maps.InfoWindow();
function SetMarkers() {
var geocoder = new google.maps.Geocoder();
$('#btnTrainer').click(function () {
var suburb = $("#address").val();
$.ajax({
type: "POST",
url: '#Url.Action("ShowAll", "Map")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "suburb": suburb }),
cache: false,
dataType: "json",
success: function (myData) {
for (i = 0; i < myData.length; i++) {
var data = myData[i];
var name = myData[i].FirstName;
var address = myData[i].Address;
geocoder.geocode({ 'address': data.Address },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "Trainer" + " "
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infoWindow.setContent(name + "," + address);
infoWindow.open(map, marker);
}
})(marker, i));
}
else {
console.log("We can't found the address, GoogleMaps say..." + status);
}
});
};
}
})
})
}
</script>

Autocompletion en show on map

I have tried to make autocompletion for my application and show this to my Google maps but it doesn't works well.
The code is in a seperate js file called autocomplete.js
I already have a google maps in app so I want to use the same.
The id of google map is: googleMap
The id of search button is: autosearch
The id of input is: autoinput
"use strict";
var input = document.getElementById('autoinput');
var options = {
bounds: defaultBounds,
types: ['establishment']
};
autocomplete = new google.maps.places.Autocomplete(input, options);
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
var input = document.getElementById('autoinput');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'be'}
};
function fillInAddress() {
var place = autocomplete.getPlace();
var defaultBounds = document.getElementById('googleMap')(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
var input = document.getElementById('autoinput');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
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)
};
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
};
I changed code etc but i guess i deleted something that i need.
This is the other js file for geolocation called locationSearch.js:
var google;
$( document ).ready(function() {
zoekLocatie();
});
function zoekLocatie() {
var output = document.getElementById("googleMap");
navigator.geolocation.getCurrentPosition(success, error);
output.innerHTML = "<p>Looking for your location...</p>";
if (!navigator.geolocation) {
output.innerHTML = "<p>Your browser doesn't support geolocation</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var mapProp = {
center: new google.maps.LatLng(latitude, longitude),
zoom: 18,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
geocodeLatLng(geocoder, map, infowindow);
function geocodeLatLng(geocoder, map, infowindow) {
var input = latitude + "," + longitude;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(18);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
address.innerHTML = results[1].formatted_address;
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
you have a error here
use strict";
you should remove the "
And where you call your google map function ?

Working with two google maps

Hi I need some help with the following:
I am trying to get two maps to display two different things.
My problem is, on the first map I would like to click on a link in the infowindow (see this) when I do click on that link, I would like that marker to display alone on the second map at its location.
here is my code. Thank you for any help.
$(document).ready(function() {
var map;
var service;
function initialise(location) {
console.log("location:" + location);
var currentLocation = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
var mapOption = {
center : currentLocation,
zoom : 14,
mapTypeId : google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOption);
var marker = new google.maps.Marker({
position : currentLocation,
map : map,
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
//service = new google.maps.places.PlacesService(map);
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
function handleSearchResults(results, status) {
console.log(results)
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map : map,
position : place.geometry.location
});
var content = '<p>See this</p>'
var infowindow = new google.maps.InfoWindow({
content:('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + content)
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
var latitude = this.position.lat();
var longitude = this.position.lng();
console.log(this.position);
});
}
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
var input = $("#search").val();
var query = (input != '' )? input : "restaurant";
performSearch(query);
});
function performSearch(q){
var request ={
bounds: map.getBounds(),
query:String(q)
};
service.textSearch(request, callback);
}
}
function initializer() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
});
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
var marker = new google.maps.Marker({
position : initialLocation,
map : map,
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
}, function() {
handleNoGeolocation(browserSupportFlag);
});
}
}
function initializer_2() {
var mapOption2 = {
center : new google.maps.LatLng(41.923, 12.513),
zoom : 14,
mapTypeId : google.maps.MapTypeId.ROADMAP,
};
var marker = new google.maps.Marker({
// need the position of marker
//position : currentLocation,
map : map,
});
map = new google.maps.Map(document.getElementById("map-canvas2"), mapOption2);
}
google.maps.event.addDomListener(window, 'load', initializer);
google.maps.event.addDomListener(window, 'load', initializer_2);
$(".getSearch").click(function () {
navigator.geolocation.getCurrentPosition(initialise);
});
});

how to get center latitude and longitude in route between two location

I am using google map to find route between two location.i want to get center latitude and longitude of the route. can u please tell me how to get center of the route.i am using the below code for getting routes,Thanks in advance
var map;
var directionsDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var infoWindow;
var service;
var lat1 = 0;
var lng1;
function pre_initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
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.InfoWindow({
map: map,
position: pos,
content: 'Current Location.'
});
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var addressfrom = document.getElementById("from").value;
var addressto = document.getElementById("to").value;
var geocoder = new google.maps.Geocoder();
var coords = new google.maps.LatLng(0, 0);
alert(lat1);
coords = geocoder.geocode({ 'address': addressfrom }, function (results, status) {
results[0].geometry.location.lat();
results[0].geometry.location.lng();
});
directionsService = new google.maps.DirectionsService();
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)
// Instantiate an info window to hold step text.
infoWindow = new google.maps.InfoWindow();
stepDisplay = new google.maps.InfoWindow();
calcRoute();
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
radius: 100,
types: ['hospital', 'cafe', 'restaurant', 'food', 'bar'],
keyword: 'best view'
};
service = new google.maps.places.PlacesService(map);
//service.nearbySearch(request, callback);
service.radarSearch(request, callback);
//service.textSearch(request, callback);
}
function callback(results, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
for (var i = 0, result; result = results[i]; i++) {
createMarker(result);
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon:
{
// Star
path: 'M 0,-24 6,-7 24,-7 10,4 15,21 0,11 -15,21 -10,4 -24,-7 -6,-7 z',
fillColor: '#ff0000',
fillOpacity: 1,
scale: 1 / 4,
strokeColor: '#bd8d2c',
strokeWeight: 1
}
});
google.maps.event.addListener(marker, 'click', function () {
service.getDetails(place, function (result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
infoWindow.setContent(result.name);
infoWindow.open(map, marker);
});
});
}
function calcRoute() {
// First, remove any existing markers from the map.
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}
// Now, clear the array itself.
markerArray = [];
var start = document.getElementById('from').value;
var end = document.getElementById('to').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var warnings = document.getElementById('warnings_panel');
warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response);
}
});
}
function showSteps(directionResult) {
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_point,
map: map
});
attachInstructionText(marker, myRoute.steps[i].instructions);
markerArray[i] = marker;
}
}
function attachInstructionText(marker, text) {
google.maps.event.addListener(marker, 'click', function () {
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
</script>
Refer to the code below:
self.adjustPosition = function () {
var lat = 0, lng = 0;
if (self.nearbyPlaces().length == 0) {
return false;
}
for (var i = 0; i < self.nearbyPlaces().length; i++) {
lat += self.nearbyPlaces()[i].latitude;
lng += self.nearbyPlaces()[i].longitude;
}
lat = lat / self.nearbyPlaces().length;
lng = lng / self.nearbyPlaces().length;
self.map.setCenter(new window.google.maps.LatLng(lat, lng));
};

Google maps api and geolocation, Javascript and Html

Hey I'm new to the google maps api, and I have an embedded map, i'm using geolocation to get the users lat and long, and i'm then filling in the gaps in the maps api. The map, however doesn't work when I use the generated lat and long, but does work if i just type one in
Non-working code:
var map;
var infowindow;
function initialize() {
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position)
{
var latlon = new google.maps.LatLng( position.coords.latitude + "," + position.coords.longitude );
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon,
zoom: 15,
disableDefaultUI: true
});
var request = {
location: latlon,
radius: 555,
types: ['bar']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
alert(place.name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Working code
var map;
var infowindow;
function initialize() {
var latlon = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon,
zoom: 15,
disableDefaultUI: true
});
var request = {
location: latlon,
radius: 555,
types: ['bar']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
alert(place.name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Any help if appreciated :)
Replace your line:
var latlon = new google.maps.LatLng
(position.coords.latitude + "," + position.coords.longitude);
with
var latlon = new google.maps.LatLng
(position.coords.latitude, position.coords.longitude);
The problem is in concatenating two values into one where constructor expects two parameters.

Categories

Resources