Google Places API, additional marker (manually added) to results - javascript

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.

Related

Javascript - Determine if user current location within KML layer of google maps

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

Hide Markers on Click with Google Maps API

I am building a search form using Google Maps Javascript V3 API. I would like to add some filters that will hide certain types of markers on the map when clicked. The markers to hide are represented with
locations[i][11] == 'Other'
HTML:
Hide Other Markers
JavaScript:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
};
var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var locations = <?php echo json_encode($locations_array); ?>;
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var content = '';
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addDomListener(document.getElementsByClassName('hideOtherMarkers')[0], 'click', function() {
if (locations[i][11] == 'Other') {
marker.setVisible(false); // maps API hide call
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
When I click the link nothing fires, verified with alerts. I also tried google.maps.event.addListener (without Dom) with no success.
As commented by geocodezip this approach will not work, because i will always point behind the end of locations. Additionally this would hide at best 1 marker (the last marker that has been created).
Possible approach:
Store the visible-state of the markers in a MVCObject:
map-options:
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
//that's the property where we store the state
visibility:new google.maps.MVCObject
};
inside the loop, after the creation of marker:
//when the state is not set yet, set it
if(typeof map.get('visibility').get(locations[i][11])==='undefined'){
map.get('visibility').set(locations[i][11],true);
}
//bind the visible-property of the marker to the state
marker.bindTo('visible',map.get('visibility'),locations[i][11]);
add the listener(outside of the loop):
google.maps.event.addDomListener(
document.getElementsByClassName('hideOtherMarkers')[0],
'click',
function() {
//simply set the desired property of the MVCObject to false
map.get('visibility').set('Other',false);
});
Demo: http://jsfiddle.net/doktormolle/5L2392mL/

how to open popup on click of a marker from the directions service?

UPDATE
when i click green marker,it's display address of location.can i change it?
LATER EDIT :
is it possible to open popup on click of a marker from the directions service?
or try the other way like only hide a marker from the directions service(green marker) and display only red marker(hide only green marker not it's route)?is it good way?
if not possible, please suggest some alternative ideas.
OLDER:
i have a two types of marker on google map.the red marker is normal marker which represent location.and green marker is route marker(its represent many of waypoints of the map).
I modify the infowindow with textbox.which is open on click red marker.
actually i am trying to do is, first i place multiple markers on google map then i draw route between this markers.this thing is done.reminder thing is on click green marker one popup is opened in which user enter price and then click the button.then i got this value and store it to database.
the problem is:
(1) how to open same infowindow on click of green marker?
in short,how to write a code for display infowindow on click of of green marker.
how to find click event of green marker?
code is:
<script type="text/javascript">
var markerarray=new Array();
//for way points
var waypts=[];
//array in json format for placing multiple marker
var locations = <?php echo json_encode($lat1);?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
<!-- ************* for placing markers ************ -->
var marker, i;
for (i = 0; i < locations.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][3], locations[i][4]),
map: map //enable if you want marker
});
//push value into way points
waypts.push({
location:locations[i][0],
stopover:true
});
//create array for polyline
markerarray[i] = marker.getPosition();//(Array(locations[i][5], locations[i][6]));
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var data='<div style="height:150px !important"><table><tr><td>Enter Price</td></tr><tr><td><input type="text" name="prc" id="prc" /></td></tr></table></div>';
infowindow.setContent(data);
infowindow.open(map, marker);
}
})(marker, i));
}
<!-- ************** for route between markers ******************* -->
var first=locations[locations.length-1][0];
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
//directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: 'red',//"black",
strokeOpacity: 1.0,
strokeWeight: 3
}
});
var start = locations[0][0];//"Bopal, Ahmedabad, Gujarat, India";
var end = locations[locations.length-1][0];//"Nikol, Ahmedabad, Gujarat, India";
//remove start destination from array
waypts.shift();
//remove end destination from array
waypts.pop();
var request = {
origin:start,
destination:end,
waypoints:waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
directionsDisplay.setMap(map);
</script>
Thanks in advance.
It is not impossible but it will take some time for code, The way is if you are using for mobile device then you need to accelerator from your device and call geolocation function on position change I think you understand and the second method is from purely javascript method for that you need to call your geolocation function within set Interval understand also draw line separately from marker your marker function only calls within set Intervals for getting your current location with infowindow. Example is :
var map;
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
//keep this in setInterval
// Try HTML5 geolocation
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: 'Location found using HTML5.'
});
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);
}
//close here your set interval
google.maps.event.addDomListener(window, 'load', initialize);
It's possible. You can hide the default marker such that you can build a custom marker on the clicked location. This code is to hide the marker.
var rendererOptions = {
suppressMarkers : true
}
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

How to find nearby hospitals using google map api and javascript

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

Allow user to create only one Google Maps marker at a time

I have the following code that allows a user to click somewhere on the map and it records the GPS location of wherever they click. It works properly on the backend but whenever the user clicks more than once it leaves multiple markers on the map. It always keeps whatever the last location is so it works but it is somewhat confusing for the user who doesn't know what is going on on the backend. Is there some little trick I can do to make it so that whenever the user clicks to create a new marker the old one is removed?
code:
var map;
var GPSlocation;
function initialize() {
var haightAshbury = new google.maps.LatLng(37.7699298, -93.4469157);
var mapOptions = {
zoom: 4,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
function addMarker(location) {
//I save the location right here
GPSlocation = location;
document.getElementById("GPSlocation").value = GPSlocation;
marker = new google.maps.Marker({
position: location,
map: map
});
}
Just use setPosition method of google.maps.Marker instance:
var map,
GPSlocation,
marker; // <-- Added
// ... snip ...
function addMarker(location) {
// ... snip ...
if (!marker) {
// Create the marker if it doesn't exist
marker = new google.maps.Marker({
position: location,
map: map
});
}
// Otherwise, simply update its location on the map.
else { marker.setPosition(location); }
}
Make the marker a global variable by declaring it outside your function:
var marker;
function addMarker(location) {
GPSlocation = location;
document.getElementById("GPSlocation").value = GPSlocation;
marker = new google.maps.Marker({
position: location,
map: map
});
}
You can also make it more efficient by only updating the location of the marker rather than creating a new object:
var marker;
function addMarker(location) {
GPSlocation = location;
document.getElementById("GPSlocation").value = GPSlocation;
if (!marker) {
marker = new google.maps.Marker({
position: location,
map: map
});
} else {
marker.setPosition(location);
}
}

Categories