var MapApiApplication = {
myCurrentPosition : "",
mapOptions : "",
marker : "",
initialize : function(){
MapApiApplication.myCurrentPosition = new google.maps.LatLng(10.112293000000000000, 76.352684500000010000);
MapApiApplication.mapOptions = {
zoom: 13,
center: MapApiApplication.myCurrentPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
MapApiApplication.map = new google.maps.Map(document.getElementById('map-canvas'), MapApiApplication.mapOptions);
MapApiApplication.marker = new google.maps.Marker({
position: MapApiApplication.myCurrentPosition,
map: MapApiApplication.map,
title: 'Here You are'
});
},
};
I have the current position's latitude and longitude. How can i find nearby hospitals locations using only javascript and google maps api.
You need to use the Places Library. In the Place Search Requests you can specify a type - which categorizes what "type" of place you are searching for. According to the Supported Place Types by Google Places API, there are hospital and health types - which would probably be your best bet to get hospitals in your search response.
I had a chance to work on it recently.
Here is the working code snippet:
// comments inline
var map;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(19.107567, 72.8335); // sample location to start with: Mumbai, India
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 200,
types: ['hospital', 'health'] // this is where you set the map to get the hospitals and health related places
};
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);
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<div id="map-canvas"></div>
It is important to note that the places wouldnt be marked onto the map if you load the library and Javascript at the end of <body> tag.
actually i require an api to find hospitals near me.the thing is i require it for thunkable.Can u tell me how to use the above api(https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places) for the same
Related
I'm trying to build a little app with the Google Map API, and since it's my first javascript app (I already know about the language, but I almost never use it), I'm struggling with a little problem.
I'm trying to get the elevation related to a marker, using the ElevationService, in order to push the two datas ({marker, elevation}) into an array. However, the line where I push the datas into the array is hit before the callback function for getElevationForLocations has been called, resulting in the push of an undefined data (elevation).
I think I should use an asynchronous function in order to wait for the callback to be executed before the data has been pushed, but I don't know how to use it.
Could anyone give me indications on that ?
Thanks a lot,
Méta
P.S.: Here is my script
var markers = [];
function initMap()
{
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -25.363882, lng: 131.044922 },
mapTypeId: 'terrain'
});
var elevator = new google.maps.ElevationService;
map.addListener('click', function(e) {
addMarker(e.latLng, map, elevator);
});
}
function getElevation(location, elevator) {
var elevation;
// Initiate the location request
elevator.getElevationForLocations({
'locations': [location]
}, function(results, status)
{
if (status === 'OK') {
// Retrieve the first result
if (results[0]) {
return results[0].elevation;
}
}
});
}
function placeMarkerAndPanTo(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
map.panTo(latLng);
return marker;
//markers.push(marker);
}
function addMarker(location, map, elevator)
{ var marker = placeMarkerAndPanTo(location, map);
var elevation = getElevation(location, elevator);
markers.push({marker, elevation});
}
Here is a simplified version of your code, using what I described in my comment.
var markers = [];
var elevator = new google.maps.ElevationService;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: -25.363882,
lng: 131.044922
},
mapTypeId: 'terrain'
});
map.addListener('click', function(e) {
addMarker(e.latLng);
});
}
function addMarker(location) {
elevator.getElevationForLocations({
'locations': [location]
}, function(results, status) {
if (status === 'OK') {
// Retrieve the first result
if (results[0]) {
var marker = new google.maps.Marker({
position: location,
map: map
});
map.panTo(location);
markers.push({
marker: marker,
elevation: results[0].elevation
});
console.log(markers);
}
}
});
}
google.maps.event.addDomListener(window, 'load', initMap);
#map {
height: 200px;
}
<script src="//maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
Edit: Seems there is a problem loading the API from the snippet at the moment (at least for me, it is crashing my browser), so here is a working JSFiddle as well.
Hi i have trouble to find what case a problem to showing the way point on goggle maps as there were no changes in the code for a wile. way point stop showing about last week. im not familiar with google api
var map = null;
var markerArray = []; //create a global array to store markers
var myPoints =
[ [52.664167, -8.509825,' HQ','favicon.ico'] ,[52.836346, -6.913117,'point 1','http://maps.google.com/mapfiles/ms/icons/red.png ' ],[52.836202, -6.912101,'point2','http://maps.google.com/mapfiles/ms/icons/red.png ' ]];
function initialize() {
var myOptions = {
zoom:7,
center: new google.maps.LatLng(53.112, -7.448),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
var mcOptions = {
gridSize: 30,
maxZoom: 15
};
var mc = new MarkerClusterer(map, [], mcOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Add markers to the map
// Set up markers based on the number of elements within the myPoints array
for(var i=0; i<myPoints.length; i++){
createMarker(new google.maps.LatLng(myPoints[i][0], myPoints[i][1]), myPoints[i][2], myPoints[i][3]);
}
mc.addMarkers(markerArray , true);
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function createMarker(latlng, html, icons) {
var contentString = html;
var links = icons;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: links ,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
// marker.setAnimation(google.maps.Animation.BOUNCE);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
markerArray.push(marker); //push local var marker into global array
}
window.onload = initialize;
<script src="https://maps.googleapis.com/maps/api/js?v=3"
type="text/javascript"></script>
<div id="map" style="width: 800px; height: 750px;" ></div>
Any suggestions?
It seems that you are using MarkerClusterer which is a part of google maps utility library, which was moved recently. Somebody probably referenced the library straight from code.google.com/svn/... in your project, where it's not available anymore and that's why it's broken. You need to find all libraries which are referenced from https://google-maps-utility-library-v3.googlecode.com/svn and replace then with your own links.
Check this SO question, user had very similar issues to yours.
Also! check this question and answers on SO!!, there are users who experienced issues with the same library, to get more information. Read all answers, as replacing https://google-maps-utility-library-v3.googlecode.com/svn with https://rawgit.com/googlemaps/... is not a correct solution, you should download the library assets into your project and reference them from there or use CDN (but not git!).
I am trying to check if user location / Google marker inside the KML layer or not.
Is there any event of KML to determine this?
Or I can check after marker placed on the google map?
Any idea?
My sample code is here.
is there any suggestion or sample code?
Waiting for your kind response.
Thanks in advance.
var map;
function initialize() {
var chicago = new google.maps.LatLng(49.051078, -122.314221);
var mapOptions = {
zoom: 11,
center: chicago
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://aeronnovation.ae/NoFlyZoneFile/doc.kml',
preserveViewport: true
});
ctaLayer.setMap(map);
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: 'You are here'
});
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);
}
google.maps.event.addDomListener(window, 'load', initialize);
KmlLayer doesn't allow access to the underlying polygon data. You can do it with FusionTables (if you import your KML data) or a third party KML parser (like geoxml3 or geoxml-v3)
example using geoxml3
example using FusionTables
example using geoxml3 with your data through a proxy
My javascript isn't too hot, I'm trying to add a manual marker onto a number of locations gathered from the Google Places API.
I followed this post to get to my following code (with a few amendments):
<script type="text/javascript">
var map;
var infowindow;
var service ;
base_Icon_festival = "https://maps.gstatic.com/mapfiles/ms2/micons/volcano.png";
shadow_festival = "https://maps.gstatic.com/mapfiles/ms2/micons/volcano.shadow.png";
function initialize(lat,lng)
{
var origin = new google.maps.LatLng(lat,lng);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.HYBRID,
center: origin,
zoom: 14,
scrollwheel: false,
});
var request = {
location: origin,
radius: 2500,
types: ['train_station','bus_station','subway_station','airport']
};
infowindow = new google.maps.InfoWindow();
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]);
}
}
}
base_Icon_train = "http://maps.google.com/mapfiles/ms/icons/red-dot.png";
base_Icon_bus = "http://maps.google.com/mapfiles/ms/icons/green-dot.png";
base_Icon_subway = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png";
base_Icon_airport = "http://maps.google.com/mapfiles/ms/icons/yellow.png";
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker;
var icon_to_use;
if (place.types.indexOf('train_station') != -1) {
icon_to_use = base_Icon_train;
} else if (place.types.indexOf('bus_station') != -1) {
icon_to_use = base_Icon_bus;
} else if (place.types.indexOf('subway_station') != -1) {
icon_to_use = base_Icon_subway;
} else if (place.types.indexOf('airport') != -1) {
icon_to_use = base_Icon_airport;
}
marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon_to_use
});
var content='<strong style="font-size:1.2em">'+place.name+'</strong>'+
'<br/><strong>Latitude: </strong>'+placeLoc.lat()+
'<br/><strong>Longitude: </strong>'+placeLoc.lng()+
'<br/><strong>Type: </strong>'+place.types[0];
//make a request for further details
service.getDetails({reference:place.reference}, function (place, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
more_content='<hr/><strong>Details';
if(place.website)
{
more_content+='<br/><br/><strong>'+place.website+'';
}
}
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content+more_content);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', function(){initialize(<?php echo $coordinated; ?>);});
</script>
<div id="map" style="height:400px;"></div>
Now I would like to manually add another marker which is located at the center of the map (ie, the variable origin which is currently being pulled from a PHP variable - var origin = new google.maps.LatLng(lat,lng);). I also need this marker to have a different icon associated with it (base_Icon_festival and shadow_festival respectively).
I'm not sure how to manually add another marker to the ones already gathered by the places API?
End goal: have a festival icon marker at the center of the map and a number of public transport markers surrounding it, resulting code to go on individual festival pages of a website.
Thanks in advance to anyone who can help.
In the Google Maps API, markers are added to the map by creating a Marker object and setting the map property. This is the snippet in your code that adds the existing Markers.
marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon_to_use
});
To add a new marker you would just replace the position and icon properties with your values.
new google.maps.Marker({
map: map,
position: origin,
icon: shadow_festival
});
This code can probably be added at the end of the Callback function and if you don't need the actual marker object for anything else, you can just create the Marker object and never assign it.
There is an example from the Google Maps API docs here.
I have a database containing addresses that are accurate to building level. When I put these manually into Google Map's search, Google Maps finds them no problem - the markers appears right over the correct building. However, when I pass these same addresses to the Google Maps API geocoder using the below code, the markers show up only on the street and not the building.
How do I increase the accuracy?
HTML/PHP:
<div id="addressline"><?php echo theaddress(); ?></div>
JS:
function myGeocodeFirst() {
geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': document.getElementById("addressline").innerHTML},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
firstLoc = results[0].geometry.location;
map = new google.maps.Map(document.getElementById("map_canvas"),
{
center: firstLoc,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
markers = new google.maps.Marker({
position: firstLoc,
map: map,
});
}
else {
document.getElementById("text_status").value = status;
}
}
);
}
window.onload=myGeocodeFirst;
Google Maps uses a number of different data sources to locate search results on the map.
The entry you are seeing that is "correct" is a Places database entry. See this page and enter you search string (St Clement’s Church, Edge Lane, Chorlton, M21 9JF).
The geocoder gets is designed to return coordinates for postal addresses, there is not enough information in your string for it to return accurate results:
http://www.geocodezip.com/v3_example_geo2.asp?addr1=St%20Clement%E2%80%99s%20Church,%20Edge%20Lane,%20Chorlton,%20M21%209JF&geocode=1
It looks like it is just returning the geocode for the postcode:
Manchester M21 9JF, UK (53.4414411, -2.285287100000005)
It does look like the geocoder does have that location in it. If I use "St Clement’s Church, Edge Lane", it seems to get the "rooftop" geocode (although it reports "APPROXIMATE")
http://www.geocodezip.com/v3_example_geo2.asp?addr1=St%20Clement%E2%80%99s%20Church,%20Edge%20Lane,%20Chorlton,%20M21%209JF&geocode=1&addr2=St%20Clement%E2%80%99s%20Church,%20Edge%20Lane&geocode=2
St Clement's Church, 6 Edge Ln, Manchester, Lancashire M21 9JF, UK (53.4406823, -2.283755499999984)
proof of concept fiddle
code snippet:
var geocoder, map, service, infowindow, bounds;
function initialize() {
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 request = {
query: "St Clement’s Church, Edge Lane, Chorlton, M21 9JF"
}
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
bounds = new google.maps.LatLngBounds();
service.textSearch(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];
var marker = createMarker(results[i]);
bounds.extend(marker.getPosition())
}
map.fitBounds(bounds);
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(place.name);
infowindow.open(map, this);
});
return marker;
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas"></div>
Basically there is a name and an address. Google database can have other name for the same location. You can read my answer here: http://www.stackoverflow.com/questions/12788664/google-maps-api-geocode-returns-different-co-ordinates-then-google-maps/12790012#12790012. In the google response you need to loop through the placemark object to find the most similar location.