get place within the given lat and long in ajax - javascript

i am in a trouble to find the places within the lat, long and radius using ajax or javascript , i used a ajax code to find this but getting error,
my code is :
$.ajax({ url: 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?',
data: {
location:'-33.8670522,151.1957362',
radius:500,
sensor:false,
key:'AIzaSyAImBQiqvaXOQtqeK8VC-9I96kMmB6Mz7I'},
dataType: "json",
type: "GET", //or POST if you want => update your php in that case
success: function( data ) {
for(var i in data.results){
alert(data.results[i]);
}
},
error: function (request, status, error) {
alert("error");
//handle errors
}
});
it gets the result error, please help me to find this
Thanks

try the following code to get places from near by locations
function initialize(arg)
{
directionsDisplay = new google.maps.DirectionsRenderer();
mapmarker="img/pois/"+arg+".png";
geocoder = new google.maps.Geocoder();
var location = new google.maps.LatLng(11.21989,78.16811099999995);
map = new google.maps.Map(document.getElementById('googleMap'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: location,
zoom: 15
});
directionsDisplay.setMap(map);
var request = {
location: location,
radius: '5000',
types: [arg]
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
//google.maps.event.addDomListener(window, 'load', initialize);
function callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for (var i = 0; i < results.length; i++)
{
var place = results[i];
createMarker(results[i]);
}
}
}

Related

How to attach .then on on google maps places library services

https://developers.google.com/maps/documentation/javascript/places
var map;
var service;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500',
type: ['restaurant']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
This is the approach google has mentioned in their docs
But I need to return the result sent by service.nearbySearch to callback(results, status)
Insteed of using callback I wanna do it using .then or await
something like
Get result of service.nearbySearch into variable (e.g. result__ )
let result__ = await service.nearbySearch(request);
or
service.nearbySearch(request)
.then(()=>{})

how to use json ajax for google map markers

I try to use the Json Ajax for google map markers.So after clicking on the button run Ajax, I get a problem with it. it's not display markers
Should change be made?
Where is my problem?
this is My Action after run ajax:
[HttpPost]
public ActionResult AsMapAjax(string jobid,string subid,string Searchitem)
{
string markers = "[";
foreach (var item in UnitOfWork.WD.GetAll())
{
markers += "{";
markers += string.Format("'title': '{0}',", "Test");
markers += string.Format("'lat': '{0}',", item.Lat);
markers += string.Format("'lng': '{0}',", item.Lng);
markers += string.Format("'description': '{0}'", "www.google.com");
markers += "},";
}
markers += "];";
var mark= new MvcHtmlString(markers);
return Json(new { success = true, responseText = mark }, JsonRequestBehavior.AllowGet);
}
}
and my jquery ajax(scripts):
navigator.geolocation.getCurrentPosition(function (p) {
var latlng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var mapOptions = {
center: latlng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
//You re Here
var iconoMarca = "../../images/URHere.gif";
mymarker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
map: map,
icon: iconoMarca,
position: latlng
});
$('#prt').on('click', function () {
var Subid = document.getElementById("bluee").value;
var jobid = document.getElementById("Jobs").value;
var Searchitem = document.getElementById("SearchItem").value;
$.ajax({
type: "post",
url: "/My/AsMapAjax",
dataType: 'json',
data: { subid:Subid,jobid:jobid,Searchitem:Searchitem},
success: function (response) {
if (response != null && response.success) {
//alert(response.responseText);
markers=response.responseText;
} else {
alert("there is a problem!");
}
},
error: function (response) {
alert("Sorry!try again please.");
}
}
)
///////
//label
var numberMarkerImg = {
url: '../../images/shapemarker.png',
size: new google.maps.Size(32, 38),
scaledSize: new google.maps.Size(32, 38),
labelOrigin: new google.maps.Point(21,42)
};
var markerLabel = 'Test';
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
//label
label:markerLabel ,
title: data.title,
icon:numberMarkerImg,
animation: google.maps.Animation.DROP
});
( function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
window.location.href = "/My/sargarmi";
});
})
(marker, data);
}
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
});
but the markers not display ! how to fix this problem?
or is other way for this question?
thanks a lot
Your question does not explain what specific problem you are experiencing. So i am going to give you a simple - working solution which improves some of the stuff you did.
Let's start with your server method. You are building the stringified version of a json array by string concatenation. That is unnecessary and error prone. Why not let the JSON serializer which is part of the mvc framework to do that for you ?
Create a simple class to represent your marker
public class Marker
{
public string Title { set; get; }
public double Lat { set; get; }
public double Lng { set; get; }
}
Now in your action method, Build a list of this Marker class and you can pass that to the Json method.
[System.Web.Mvc.HttpPost]
public ActionResult AsMapAjax(string jobid, string subid, string Searchitem)
{
//Hard coded for demo. You may replace with values from db
var list = new List<Marker>
{
new Marker() { Title="AA" ,Lat = -33.890542, Lng=151.274856 },
new Marker() { Title="BB", Lat = -33.923036, Lng=151.259052 },
new Marker() { Title="CC" ,Lat = -34.028249, Lng=151.157507 },
};
return Json(new { success = true, responseText = list });
}
Now in your client side, you make the ajax call to this action method, read the response coming back and add markers.
$(function() {
$('#prt').on('click', function() {
initMap();
});
});
function initMap() {
//read the parameter values you want to send to server
var searchItem =$("#SearchItem").val();
var jobs=$("#Jobs").val();
var subid = $("#bluee").val();
var map = new google.maps.Map(document.getElementById('map'),
{
zoom: 8
});
var url = "#Url.Action("AsMapAjax", "Home")";
$.post(url, { searchTerm: searchItem,jobid: jobs,subid : subid },function(res) {
if (res.success) {
var latLng;
$.each(res.responseText,function(i, item) {
latLng = new google.maps.LatLng(item.Lat, item.Lng);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
});
map.setCenter(latLng);
}
});
}
I am using the Url.Action method to generate the correct relative url to the action method as my script was inside a razor code block. If you are using this code in an external javascript file, follow the solution described in this post to handle that case

Uncaught TypeError: Cannot read property 'targetLat' of undefined

well i just put some markers on google map and it works as i want and marker is displayed as required on the map but i get this error in the console i don't know why which makes the app runs on android but not on windows phone
function initMap() {
var map;
var faisalabad = { lat: 30.044281, lng: 31.340002 };
$('#locaitonBtn').click(function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(latlng);
});
}
})
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: faisalabad,
disableDefaultUI: true
});
$.ajax({
async:false,
url: "https://someUrl",
method: "GET",
dataType: 'json',
success: function (data) {
var infowindow = new google.maps.InfoWindow();
for (i = 0; i <= data.targets.length; i++) {
var myLatLng = new google.maps.LatLng(data.targets[i].targetLat, data.targets[i].targetLong);
myMarker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: myLatLng
});
google.maps.event.addListener(myMarker, 'click', (function (myMarker, i) {
return function () {
infowindow.setContent(data.targets[i].targetName);
infowindow.open(map, myMarker);
}
})(myMarker, i));
}
}
})
}
$.ajax({
async:false,
url: "https://someUrl",
method: "GET",
dataType: 'json',
success: function (data) {
var infowindow = new google.maps.InfoWindow();
for (var i = 0; i <= data.targets.length; i++) {
var myLatLng = new google.maps.LatLng(data.targets[i].targetLat, data.targets[i].targetLong);
var myMarker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: myLatLng
});
google.maps.event.addListener(myMarker, 'click', (function (myMarker, i, data) {
return function () {
infowindow.setContent(data.targets[i].targetName);
infowindow.open(map, myMarker);
}
})(myMarker, i, data));
}
}
});
changed 3 things:
var i = 0 in for statement
var myMarker = new google.maps.Marker ... (it's not a global)
injecting data to the anonymous click listener function because it has no scope on the data object.
i'm not sure this works because i have no test envoirement for it. but hope it helps you to figure out the failure.
i think the first point was the failure because you tried to use a global i in your for loop and reset it anywhere else in your code. so the array index returns undefined
Well I couldn't solve the problem or find an answer to it anywhere so i added the success function to a try catch block so it don't console the error and i can run the app now on windows phone

Google Maps google.maps.places.PlacesService typeerror undefined

Following the code nearly exactly from: https://developers.google.com/maps/documentation/javascript/places#TextSearchRequests
When
service = new google.maps.places.PlacesService(map);
is called, the console gives me an undefined type error:
util.js:22 Uncaught TypeError: Cannot read property 'innerHTML' of undefined
My code is below. Anyone know what is happening?
HTML
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDo5LxyVUv5EwGQBwaveIF4d0MaIVD_Dd8&libraries=places"></script>
JS
function initMap(userLocation) {
map = new google.maps.Map(document.getElementById('map'), {
center: userLocation,
zoom: radius
});
infowindow = new google.maps.InfoWindow();
}
function textSearch(query) {
var service;
var request = {
location: userLocation,
query: query
};
service = new google.maps.places.PlacesService(map);
service.textSearch(request, cb);
}
function cb(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
// createMarker(results[i]);
console.log(place);
}
}
}
initMap(userLocation); // userLocation is a latLong obj, set elsewhere in the code.
textSearch('movies');

Laravel and Geocoding markers (nearby users) do not update correctly

I try to show on a google map markers that are near the current positon. If the map is dragged it will update the center coordinates and recalculate the markers around that center. The initial markers around the current users positon are showing correctly but when i drag the map they stay all the time the same. The update and the POST both is happening (my guess that the POST is not finished before the markers reload, so the old ones stay). The sourrounding markers are stored in a session variable.
Controller showNearbyUsers method:
/**
* Shows the users near the current one
*
* #return void
*/
public static function showNearbyUsers($centerlat,$centerlng)
{
try {
// Delete the session variable
if (Session::has('nearbies'))
{
Session::forget('nearbies');
}
// Define max, min for lat and lng
$centerlatlow = $centerlat-0.25;
$centerlathigh = $centerlat+0.25;
$centerlnglow = $centerlng-0.25;
$centerlnghigh = $centerlng+0.25;
$nearbies = DB::table('positions')->join('users', 'users.id', '=', 'positions.users_id')
->where('users_id', '!=', Auth::id())
->whereBetween('lat', array($centerlatlow, $centerlathigh))
->whereBetween('lng', array($centerlnglow, $centerlnghigh))
->select('positions.*', 'users.name', 'users.level')
->get();
if ($nearbies) {
return Session::put('nearbies', $nearbies);
}
} catch(\Exception $e) {
Session::flash('message', 'An error occured with your localization. Enable GPS and refresh.');
Session::flash('alert-class', 'alert-danger');
}
}
View Script
<script>
// Auto adjust map div
$(window).resize(function () {
var h = $(window).height(),
offsetTop = 220; // Calculate the top offset
$('#map_canvas').css('height', (h - offsetTop));
}).resize();
// Setup token security
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
// Attributes
var map;
var geocoder;
var markers = Array(); // Contains x,y
var users = Array(); // Contains whole user info
var current = Array();
var infoWindows = Array();
var mapCenter;
// Test initialize users array
//users = [['Brugg',47.47963,8.18465],['Aarau',47.39340,8.04312],['Baden',47.47377,8.30647]];
// Initialize the map with logged in user
function initialize() {
geocoder = new google.maps.Geocoder();
getLocation();
}
// Set nearby user markers
function setMarkers(list) {
for(var i=0; i<list[0].length; i++){
var element = (list[0])[i];
var nearbyLatLng = new google.maps.LatLng(element['lat'], element['lng']);
console.log((list[0])[i]);
markers[i] = new google.maps.Marker({
position: nearbyLatLng,
map: map,
title: element['name'],
infoWindowIndex : i
});
infoWindows[i] = new google.maps.InfoWindow({
content : element['name']
});
google.maps.event.addListener(markers[i], 'click',
function(event)
{
infoWindows[this.infoWindowIndex].open(map, this);
}
);
}
}
// Delete nearby user markers
function deleteMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
// Map dragging listener. Updates the nearby users markers
function mapDragListener() {
google.maps.event.addListener(map, 'dragend', function() {
deleteMarkers();
mapCenter = map.getCenter();
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
#if(Session::has('nearbies'))
<?php $test = Session::get('nearbies'); ?>
users = [<?php echo json_encode($test); ?>];
console.log(users);
#endif
setMarkers(users);
});
}
// Map zoom listener. Updates the nearby users markers
function mapZoomListener() {
}
// Get current user location
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
// If success in finding current position
function geoSuccess(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// Send to geocoordinates.php and save to DB
$.post("updateme/"+lat+"/"+lng);
mainMapCalc(lat, lng);
}
// If no success in finding current position
function geoError() {
alert("Please enable Geo-Location and Refresh the Website.");
}
// Set the logged in users and build up the environment
function mainMapCalc(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[1]) {
//formatted address
var address = results[0].formatted_address;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 18,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
mapCenter = map.getCenter();
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
<?php $test = Session::get('nearbies'); ?>
users = [<?php echo json_encode($test); ?>];
setMarkers(users); // Set initial nearby markers
mapDragListener(); // Register Listener
//mapZoomListener(); // TODO: Register Listener
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
} else {
alert("Geocoder Error// No results found");
}
} else {
alert("Geocoder Error// Failed due to: " + status);
}
});
}
// Show Map
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Where is here the problem?
Thanks in advance
It looks like the problem is that you are sending out the ajax request, but you are not doing anything with the returned data. Try changing
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
to
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
success: function(data, textStatus, jqXHR) {
// request succeeded
// data - response from server
},
error: function (jqXHR, textStatus, errorThrown){
// the request failed
}
});
Also note that async: false is deprecated: https://api.jquery.com/jQuery.ajax/#options, so you should use callbacks as shown above.

Categories