I have implemented a sample using Places Search of Google Maps API. I would like to fetch the number of results I am fetching. New to Google Maps API. How do I achieve this?
jsFiddle
JS:
var map;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(19.107567, 72.8335);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 500,
types: ['hospital']
};
infowindow = new google.maps.InfoWindow();
var 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]);
}
}
}
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);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Replace your callback with this:
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// Just count the number of results passed to your callback
var numResults = results.length;
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
Related
Input: user will select city and place category.
Output: google map with all places that have same category in that city.
How i can do it with google map APIs.
When i try to use places API it’s return json with geographic data but i cant use it with JavaScript or jQuery Json request.
$.getJSON( "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&keyword=cruise&key=YOUR_API_KEY", function( json ) {
console.log( "JSON Data: " + json );
});
But browser log don’t show any output.
Any example code for best way to implement my idea??!
Thank you
You're probably looking for the client-side Places Library's Nearby Search service. Take a look at this working jsfiddle.
JS code below:
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++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
Hope this helps!
with this code you need only to provide city name and place types or that you can find here:
https://developers.google.com/places/web-service/supported_types
output will show 20 places in same city with type that you passed.
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
var map;
var service;
var infowindow;
var city;
function initMap() {
var cityName = document.getElementById('cityInput').value; // text input html tag
var type = document.getElementById('subCategory').value; // select input html tag
map = new google.maps.Map(document.getElementById('map'), {zoom: 14});
var cityRequest = {
query: cityName,
fields: ['name', 'geometry'],
};
//alert("find!! : " + cityName);
service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(cityRequest, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
let city = results[0].geometry.location;
map.setCenter(city);
infowindow = new google.maps.InfoWindow();
//alert(type);
var request = {
location: city,
radius: '1000',
query: type
};
//radius is size of search area
service.textSearch(request, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) { // adding places to map
createMarker(results[i]);
}
//map.setCenter(results[0].geometry.location);
}
});
}
});
}
function createMarker(place) {
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);
});
}
</script>
With this code you will show map in you web page
<div id="map" style="height: 500px; "></div>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap&language=ar" async defer></script>
I am developing a web application and integrated google maps with java script. markers are working fine with good latitude and longitude. the route map is not shown perfectly. when search users in a route map, not showing properly. it shows different routes. it didn't clear previous route. How can I clear previous route?
Route Map Screen shot
sample maps code:
var marker= [];
var geocoder;
var map;
var directionsDisplay,directionsService;
directionsDisplay = new google.maps.DirectionsRenderer({ draggable: false, suppressMarkers: true });
directionsService = new google.maps.DirectionsService();
var request = {
travelMode: google.maps.TravelMode.DRIVING
};
googleMapCoordinates(response);
function googleMapCoordinates(response) {
setMapOnAll(null);
marker = [];
directionsDisplay.setMap(null);
directionsDisplay.setPanel(null);
$("#map").show();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(17.7254567, 83.3097112),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
var i;
for (i = 0; i < response.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(response[i].latitude, response[i].longitude),
map:map,
label:response[i].count
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("Name :"+response[i].name);
infowindow.open(map, marker);
}
})(marker, i));
/******************Direction*********************************/
if (i == 0) request.origin = marker.getPosition();
else if (i == response.length - 1) request.destination = marker.getPosition();
else {
if (!request.waypoints) request.waypoints = [];
request.waypoints.push({
location: marker.getPosition(),
stopover: true
});
}
}
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
function setMapOnAll(map) {
console.log("Set map is to empty state ");
for (var i = 0; i < marker.length; i++) {
marker[i].setMap(map);
}
}
Can any one give me an idea on how to zoom your map according to the markers. Actually I have geocoded the addresses and the markers are shown on the map. But they are not centered i.e. I have to drag the map to see the other marker.I want my map to fit bounds using the addresses that I have in my addresses array. How this can be done.? My current code for geocoding is:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var addresses = new Array();
abc = document.getElementsByTagName('td');
//loc = mydiv.getAttribute("data-addr");
var l = abc.length;
for (var i=0; i < l; i++){
if (abc[i].hasAttribute('name'))
{
addresses.push(""+abc[i].innerHTML+""); //removed single quotes here. see previous code
}
}
var len = addresses.length;
var geocoder;
var map;
var add = document.getElementById("addr").value;
window.onload = function init() {
geocoder = new google.maps.Geocoder();
var add = document.getElementById("address").value;
var latlng = codeAddress(add);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
//for (var i = 0; i < addresses.length; i++)
//{
function codeAddress(add)
{
//var addr = addresses[i];
geocoder.geocode( { 'address':add }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function createMarkers()
{
for(var i = 0; i < len; i++){
(function(addresses){
geocoder.geocode( { 'address': addresses }, function(results) {
var marker = new google.maps.Marker ({
map: map,
position: results[0].geometry.location,//error:results[0] is undefined
title: address
});
google.maps.event.addListener(marker, 'click', function() {
alert(addresses);
});
});
})(addresses[i]);
}
}
window.onload = createMarkers;
</script>
In your function where you are creating the markers you can also extend the bounds (with
function createMarkers()
{
//create the bounds for the map
var bounds = new google.maps.LatLngBounds();
for(var i = 0; i < len; i++){
(function(addresses){
geocoder.geocode( { 'address': addresses }, function(results) {
var marker = new google.maps.Marker ({
map: map,
position: results[0].geometry.location,//error:results[0] is undefined
title: address
});
google.maps.event.addListener(marker, 'click', function() {
alert(addresses);
});
});
})(addresses[i]);
//extend the bounds with each address
bounds.extend (addresses[i]);
}
//fit to the full list of bounds
map.fitBounds(bounds);
}
If you want to set a maximum zoom level no matter what the actual bounds are you can add this after the map.fitBounds (you can change the level of zoom):
var listener = google.maps.event.addListener(map, "idle", function() {
if (map.getZoom() > 10) map.setZoom(10);
google.maps.event.removeListener(listener);
});
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));
};
I'm having a problem working out how to set the zoom level for different countries, I have managed to get the map working and displaying the country, just cannot seem to work out how to set the zoom level.
Any help would be appreciated.
Thanks
George
<script type="text/javascript">
var infowindow = null;
$(document).ready(function () { initialize(); });
function initialize() {
//var geocoder = new google.maps.Geocoder();
//geocoder.geocode({ 'address': address }, function (results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
// map.setCenter(results[0].geometry.location);
// map.fitBounds(results[0].geometry.viewport);
// }
//});
var centerMap = new google.maps.LatLng(#Html.Raw(#item.strLatLong));
var myOptions = {
zoom: 4, //<<-------How can I chnage this
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("WeatherMapLocation"), myOptions);
setMarkers(map, sites);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: sites[0],
zIndex: sites[3],
html: sites[4]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
</script>
From the documentation on the Geocoder, there is a viewport and a bounds returned in the geocoder's response which can be used to center and zoom the map on the result.
if (results && results[0] && results[0].geometry && results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
working example