enter image description here
1- How to show 30 state with marker of in google map and each state has 60 cities.
2- By default only show state with marker after choose any state then show all cities of selected state with marker.
This works. Before executing the code, be sure to change the API_KEY of yours. Also leave sometime before clicking the markers. In case you click them hastily, google would respond with OVER_QUERY_LIMIT in the response and the markers couldn't be set. I just tried with 3 states and 4-6 cities of each.
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 600px;
width: 50%;
margin:0 auto;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map, geocoder, oldselectedstate="Tamilnadu", selectedstate="Tamilnadu", statemarkers={}, citymarkers={};
var cities = {"Tamilnadu":["Chennai","Namakkal","Madurai","Keeladi","Coimbatore","Kanyakumari"],"Andhra Pradesh":["Visakhapatnam","Vijayawada","Guntur","Nellore","Rajahmundry"],"Kerala":["Trivandrum","Cochin","Calicut","Quilon","Trichur"]};
var states = Object.keys(cities);
function initMap()
{
var nagpur = {lat: 21.146633, lng: 79.088860};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: nagpur
});
geocoder = new google.maps.Geocoder();
createStateMarkers();
createCityMarkers();
}
function toggleMarkers(markers, isshowmarkers)
{
console.log(markers);
for (var i = 0; i < markers.length; i++)
{
markers[i].setMap(isshowmarkers?map:null);
}
}
function toggleCityMarkers(isshowmarkers)
{
toggleMarkers(Object.values(citymarkers[isshowmarkers?selectedstate:oldselectedstate]),isshowmarkers);
}
function createMarker(position, icon, placename)
{
return new google.maps.Marker({
position: position,
map: map,
icon: icon,
customInfo: {name:placename},
});
}
function createCityMarkers()
{
if(!citymarkers[selectedstate])
{
cities[selectedstate].forEach(function(city){
geocoder.geocode({ address: city }, function (results, status) {
if(status === google.maps.GeocoderStatus.OK)
{
var location = results[0].geometry.location;
var marker = createMarker({lat:location.lat(),lng:location.lng()}, "http://maps.google.com/mapfiles/ms/icons/blue-dot.png", city);
citymarkers[selectedstate] = citymarkers[selectedstate]||{};
citymarkers[selectedstate][city] = marker;
toggleCityMarkers(false);
}
});
});
}
else
{
toggleCityMarkers(true);
}
}
function createStateMarkers()
{
states.forEach(function(item){
geocoder.geocode({ address: item }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK)
{
var location = results[0].geometry.location;
var marker = createMarker({lat:location.lat(),lng:location.lng()}, "http://maps.google.com/mapfiles/ms/icons/red-dot.png", item);
marker.addListener("click",function(){
oldselectedstate = selectedstate;
toggleCityMarkers(false);
selectedstate = this.customInfo.name;
createCityMarkers();
});
statemarkers[item]=marker;
}
});
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAFTDif2GgY6fxV1wLRjDO9fLGzgM4NRd0&callback=initMap">
</script>
</body>
</html>
Related
When I pass the address to Google Maps .com in the browser, it returns a certain name of the address on the marker(as shown in fig -1). But when I pass the postal address using Google Place and Geocoder API’s, it returns me the address and place ID with the marker(as shown in fig-2) .
As shown in images the address values returned by MAPS application is different from the one’s I am getting through the API’s.
Is it some attribute of the API which gives the name of the building or centre situated at this address?
Is it some premium service that I need to buy in order to display the exact name of building at this address ?
I have tried with various attributes of the PLACES API but not getting the value I need. using PLACE API
var address = "1900 S Jackson Rd Suite 7 MCALLEN TX";
var map;
var marker;
var service;
var request;
function initialize() {
var geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map_canvas'),
{
center : {
lat : - 33.866, lng : 151.196
},
zoom : 15
});
if (geocoder) {
geocoder.geocode( {
'address' : address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
service = new google.maps.places.PlacesService(map);
console.log(results[0].place_id);
map.setCenter(results[0].geometry.location);
console.log('resulta ddre '+results[0].formatted_address);
service.getDetails( {
placeId : (results[0].place_id)
},
function (place, status) {
var infowindow = new google.maps.InfoWindow();
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(status);
marker = new google.maps.Marker( {
map : map, position : place.geometry.location
});
console.log('<HTML ATT>'+ place.address_components+'Place ID: ' + place.place_id
+ '<Place Name>' + place.name
+ '<Formatted Address>' + place.formatted_address);
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + 'Place ID: ' + place.place_id + '<br>' + place.formatted_address +
'</div>');
infowindow.open(map, this);
});
}
});
};
}
});
}
}
When you search "1900 S Jackson Rd Suite 7 MCALLEN TX" on maps.google.com you get the location of "Pediatric Lung Center: Ayres Roberto A MD".
Please note that Geocoding service works only with street addresses, and businesses are excluded from the search. In your code you execute a geocoding request first so you get a different result. You have to execute places text search to get the same business as on maps.google.com.
Have a look at the following example:
code snippet:
var map;
var infowindow;
var address = "1900 S Jackson Rd Suite 7 MCALLEN TX";
function initMap() {
var m_center = {lat: 26.1817228, lng: -98.2098557};
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: m_center,
zoom: 16
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.textSearch({
query: address,
bounds: map.getBounds()
}, 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,
title: place.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<div id="map-canvas"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places&callback=initMap"></script>
I'm trying to put markers on a google location map API using data I put on an inedexedDB. I'm able to put the markers accurately using the data I get from the DB, but the markers' infowindow doesn't get them accurately.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<style type="text/css">
#map {
width: 700px;
height: 700px;
}
</style>
</head>
<body>
<div id="map"></div>
<button onclick="showMarker()">Show Markers </button>
<script type="text/javascript">
//prefixes of implementation that we want to test
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
//prefixes of window.IDB objects
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
var db;
var request = window.indexedDB.open("mapDB", 1);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(11.980433, 121.918866),
mapTypeId: google.maps.MapTypeId.HYBRID
});
const locData = [
{ id: "00-01", name: "Boracay", lat: 11.980433, lng: 121.918866 },
{ id: "00-02", name: "Baguio City", lat: 16.402333, lng: 120.596007 },
{ id: "00-03", name: "Isdaan", lat: 15.475479, lng: 120.596349 },
{ id: "00-04", name: "Mount Pinatubo", lat: 15.142973, lng: 120.349302 }
];
request.onerror = function(event) {
console.log("error: ");
};
request.onsuccess = function(event) {
db = request.result;
console.log("success: "+ db);
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("location", {keyPath: "id"});
for (var i in locData) {
objectStore.add(locData[i]);
}
db.onsuccess = function(event) {
showMarker();
};
}
function showMarker() {
var infowindow = new google.maps.InfoWindow();
var marker, i;
var objectStore = db.transaction("location").objectStore("location");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(cursor.value.lat, cursor.value.lng),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(cursor.value.name);
infowindow.open(map, marker);
}
})(marker, i));
cursor.continue();
}
};
}
</script>
</body>
</html>
I have tried searching and reading other sources but I can't seem to find what's the problem. Help is very much appreciated.
This is a duplicate of Google Maps JS API v3 - Simple Multiple Marker Example. You need function closure on the name of the marker.
function showMarker() {
var infowindow = new google.maps.InfoWindow();
var marker;
var objectStore = db.transaction("location").objectStore("location");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(cursor.value.lat, cursor.value.lng),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, name) {
return function() {
infowindow.setContent(name);
infowindow.open(map, marker);
}
})(marker, cursor.value.name));
cursor.continue();
}
};
}
proof of concept fiddle
I try to get the elevation of a point on a map, but the elevation function proposed by the googlemaps' API doesn't work and I don't know why.
It seems that the programm don't even get through the function.
Here my function :
var elevationService = new google.maps.ElevationService();
var requestElevation = {
'locations': gmarkers[0].getPosition()};
elevationService.getElevationForLocations(requestElevation, function(results, status) {
if (status == google.maps.ElevationStatus.OK) {
if (results[0]) {
document.getElementById('denivele_circuit').value = parseFloat(results[0].elevation.toFixed(1)) + "mètres";
}
} });
I get a javascript error with your code: Uncaught InvalidValueError: in property locations: not an Array
The locations property in the LocationElevationRequest must be an array.
from the documentation for google.maps.LocationElevationRequest object specification
An elevation request sent by the ElevationService containing the list of discrete coordinates (LatLngs) for which to return elevation data.
Properties
locations Type: Array
The discrete locations for which to retrieve elevations.
var requestElevation = {
'locations': [gmarkers[0].getPosition()]
};
proof of concept fiddle
code snippet:
var gmarkers = [];
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
gmarkers.push(marker);
var elevationService = new google.maps.ElevationService();
var requestElevation = {
'locations': [gmarkers[0].getPosition()]
};
elevationService.getElevationForLocations(requestElevation, function(results, status) {
if (status == google.maps.ElevationStatus.OK) {
if (results[0]) {
document.getElementById('denivele_circuit').value = parseFloat(results[0].elevation.toFixed(1)) + " mètres";
}
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input id="denivele_circuit" />
<div id="map_canvas"></div>
I tried using Google Maps API for 'Reverse Geocoding' to get the location by providing latitude and longitude. This gives the street address, city and country info. But I need to get the exact details like building name, shop name etc. For example, while querying the co-ordinates "72.9011206,19.0517508", Google Maps API gives "Plot No 5, VN Purav Marg, Borla, Union Park, Chembur, Mumbai, Maharashtra 400071, India". But I need to get the name of the shop "Barista Lavazza" as available in 'Google Earth' for the same co-ordinate details.
One option would be to use the Google Maps Javscript API Places library nearbySearch, search the returned results for the closest result to the requested position.
proof of concept fiddle
code snippet:
var map;
var infowindow;
var searchLoc = new google.maps.LatLng(19.0517508, 72.9011206);
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: searchLoc,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
infowindow = new google.maps.InfoWindow();
var request = {
location: searchLoc,
radius: '50'
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var bounds = new google.maps.LatLngBounds();
var distMin = Number.MAX_VALUE;
var idxMin = -1;
for (var i = 0; i < results.length; i++) {
var place = results[i];
bounds.extend(results[i].geometry.location);
var distance = google.maps.geometry.spherical.computeDistanceBetween(results[i].geometry.location, searchLoc);
if (distance < distMin) {
distMin = distance;
idxMin = i;
}
}
var marker = createMarker(results[idxMin]);
google.maps.event.trigger(marker, 'click');
}
}
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("<h2 style='color:blue'>"+place.name + "</h2><br>" + place.vicinity + "<br>" + marker.getPosition().toUrlValue(7));
infowindow.open(map, this);
});
return marker;
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script>
<div id="map_canvas"></div>
With the example below,
https://google-developers.appspot.com/maps/documentation/javascript/examples/place-search
By using nearbySearch one of the place return is "John St Square Supermarket".
How do i generate a url to show "John St Square Supermarket" in full google maps?
Right now i'm generating by appending the latitude and longitude into "http://maps.google.com/?q=" which become something like http://maps.google.com/?q=123,456
but it won't show the place's name and the correct marker.
I then tried with http://maps.google.com/?q=John St Square Supermarket
Working good... until i stumble into a place name with multiple locations. For example,
http://maps.google.com/?q=SK%20Dato%27%20Abu%20Bakar
It shows multiple location but i only need one which i already know what it's latitude and longitude is.
You can add the Latitude and Longitude to the URL using the parameter ll:
https://maps.google.com/?q=pizza+hut&ll=-33.867701,151.208471
You can also specify a default zoom level for the user using the paremeter z:
https://maps.google.com/?q=pizza+hut&ll=-33.867701,151.208471&z=12
PlacesResult.url property stands for the url of Google Places.
https://developers.google.com/maps/documentation/javascript/reference#PlaceResult
So you can do like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Place Search</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<style>
#map {
height: 400px;
width: 600px;
border: 1px solid #333;
margin-top: 0.6em;
}
</style>
<script>
var map;
var infowindow;
var service;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId : google.maps.MapTypeId.ROADMAP,
center : pyrmont,
zoom : 15
});
var request = {
location : pyrmont,
radius : 500,
types : ['store']
};
infowindow = new google.maps.InfoWindow();
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,
reference : place.reference,
name : place.name
});
google.maps.event.addListener(marker, 'click', onMarker_clicked);
}
function onMarker_clicked() {
var marker = this;
service.getDetails({
reference : marker.get("reference")
}, function(result) {
var html = marker.get("name");
if (result && "url" in result) {
marker.set("url", result.url);
}
if (marker.get("url")) {
html = "<a href='" + marker.get("url") + "' target=_blank>" + html + "</a>";
}
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>