Google Map with Local Churches, how to construct API call? - javascript

Is there are way to retrieve a map from Google using the API so that it displays a list of local churches with churches with markers?
I have the basic syntax, and I have a basic API account setup, but I am not how/if I can use the type field.
var mapOptions = {
center: new google.maps.LatLng("-33.8670522", "151.1957362"),
zoom: 11,
scrollwheel: false,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googlemaps"), mapOptions);

Yes, you can do this, using Google Places API.
I'll use JavaScript API, since you seem to have a map being built with such API.
As said in documentation:
The Places service is a self-contained library, separate from the main Maps API JavaScript code. To use the functionality contained within this library, you must first load it using the libraries parameter in the Maps API bootstrap URL:
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
After this, using JavaScript Places API you can request places by type and a radius (in meters). The maximum allowed radius is 50.000 meters.
Here a piece of code that demonstrate this:
var request = {
location: sydney,
radius: 5000,
types: ['church']
};
var service = new gm.places.PlacesService(map);
service.nearbySearch(request, handlePlaceResponse);
Obs.: In this example, handlePlaceResponse is a callback to handle the response and create the markers. See in the complete example how it works.
This will request by churches in a 5km radius from Sydney point (lat: -33.8670522, lng: 151.1957362).
To overlay markers you'll need handle the response. In the example I used only name to put as content of InfoWindow. You can see details about the response here: Place Details Responses
So, a function to create markers look like this:
/**
* Creates marker with place information from response
*/
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
Also, if you need, for types supported in place search, see this link: Place Type
Here an example using as point the used by you and 5000 meters for radius:
<html>
<head>
<title>Google Maps - Places Sample</title>
<style>
body {
margin: 0;
}
#map {
height: 600px;
width: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script>
var gm = google.maps;
var map;
var bounds;
var service;
var infowindow;
var sydney = new gm.LatLng(-33.8670522, 151.1957362);
function initialize() {
var options = {
zoom: 15,
center: sydney,
mapTypeId: gm.MapTypeId.ROADMAP,
streetViewControl: false,
scrollwheel: false
};
map = new gm.Map(document.getElementById("map"), options);
var request = {
location: sydney,
radius: 5000,
types: ['church']
};
bounds = new gm.LatLngBounds();
infowindow = new gm.InfoWindow();
service = new gm.places.PlacesService(map);
service.nearbySearch(request, handlePlaceResponse);
}
/**
* Handle place response and call #createMarker to creat marker for every place returned
*/
function handlePlaceResponse(results, status) {
if (status == gm.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
map.fitBounds(bounds);
map.setCenter(bounds.getCenter());
}
/**
* Creates marker with place information from response
*/
function createMarker(place) {
var location = place.geometry.location;
var marker = new gm.Marker({
map: map,
position: location
});
bounds.extend(location);
gm.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
gm.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

Related

Google Places API show schools and stores

Using the Google Maps API with the places library I am able to show nearby schools using the recommended method shown here.
var map;
var infowindow;
function initMap() {
var pyrmont = {lat: -33.867, lng: 151.195};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, 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);
});
}
Here's a working fiddle: https://jsfiddle.net/api/post/library/pure/
The problem is that if I also want to show nearby stores as well as schools, everyone seems to recommend simply doing this:
type: ['store', 'school']
While this technically works, the problem is the map just shows a bunch of meaningless default markers with no way of knowing what it what.
So my question is: How can I change the icon for the schools and stores? Ideally I would show a different icon for each different type.
It's no different than adding custom marker in regular map.Only thing is that you need to make api calls separately for each type.So even type: ['store', 'school'] would work and you get results but there is no type specifier in the results to tell whether it's a school or shop .Also you would need to create their separate callbacks for setting their separate icons
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
icon:"http://example.com/icon.png", //<-- only this line is enough for icon
map: map,
position: place.geometry.location
});
go through this for a better understanding
Moreover every result will have a default icon (as icon property), that can also be used
var marker = new google.maps.Marker({
icon:place.icon,
map: map,
position: place.geometry.location
});

Adding Javascript Functions to Load Google Maps C# WPF

I am trying to integrate Google Maps into a WebBrowserControl in my C# WPF program. The map loads in the control and centers on the correct latitude and longitude, however I am having a couple of errors. First of all, the map loads and after a couple of seconds I get an error box appear;
Secondly, when I am trying to add a marker on the location of the latitude and longitude, I get an error even before the map loads at all. Here is my code so far;
mapWebBrowser.NavigateToString(#"<html xmlns=""http://www.w3.org/1999/xhtml"" xmlns:v=""urn:schemas-microsoft-com:vml"">
<head>
<meta http - equiv = ""X-UA-Compatible"" content = ""IE=edge""/>
<meta name = ""viewport"" content = ""initial-scale=1.0, user-scalable=no""/>
<script type = ""text/javascript""
src = ""http://maps.google.com.mx/maps/api/js?sensor=true&language=""es"" ></script>
<script src = 'http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js'>
</script><script type = ""text/javascript"">
function initialize() {
var latlng = new google.maps.LatLng(" + latitude + ", " + longitude + #");
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(""map_canvas""), myOptions);
}
function addMarker( Lat, Long) {
var latLng = new google.maps.LatLng(Lat, Long);
marker = new google.maps.Marker({
position: latLng,
draggable: false,
animation: google.maps.Animation.DROP,
});
markers.push(marker);
var markerCluster = new MarkerClusterer(map, markers)
}
</script>
</head>
<body onload = ""initialize()"" >
<div id=""map_canvas"" style=""width:100%; height:100%""></div>
</body>
</html>");
This is the function I am attempting to use to add a marker onto the map;
function addMarker( Lat, Long) {
var latLng = new google.maps.LatLng(Lat, Long);
marker = new google.maps.Marker({
position: latLng,
draggable: false,
animation: google.maps.Animation.DROP,
});
markers.push(marker);
var markerCluster = new MarkerClusterer(map, markers)
}
Which I call in C#;
mapWebBrowser.InvokeScript("addMarker", new object[] { latitude, longitude } );
Unfortunately as I stated before both methods are causing issues.
I believe there was a change in Google's APIs back in June and they now require authentication for google maps. I don't see your API key being supplied anywhere. I would suggest you try your HTML/javascript in the browser or where you can sniff the requests and the responses and see what's going on.
If you still can't solve your problem. You may use Script Errors Suppressed too. Then this window will disappear.
webBrowser1.ScriptErrorsSuppressed = true;

My google places kml url javascript

i have a problem with my places from google maps, i already have a functionality map with a file kml in my https server, but i don't want to download and upload the map every time I make changes, not work for me only embed I need manipulated with API, so this is my code:
var map;
var src = 'MY_SERVER/points_vl.kmz';
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(20.63736, -105.22883),
zoom: 2,
});
loadKmlLayer(src, map);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = 'http://www.nearby.org.uk/google/circle.kml.php?radius=5miles&lat='+position.coords.latitude+'&long='+position.coords.longitude;
loadKmlLayer(circle, map);
map.setCenter(pos);
setTimeout(function(){
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location'
});
infowindow.setPosition(pos);
}, 2000);
});
}
}
function loadKmlLayer(src, map) {
var kmlLayer = new google.maps.KmlLayer(src, {
suppressInfoWindows: true,
preserveViewport: false,
map: map
});
google.maps.event.addListener(kmlLayer, 'click', function(event) {
var content = event.featureData.infoWindowHtml;
var testimonial = document.getElementById('capture');
testimonial.innerHTML = content;
});
}
This work fine, but have a way for direct the kml from my url of google maps places?
Using an existant Google 'My Places' map with Maps API v3 styling this thread have some idea, but not work, if you get a idea how make it will make it wonderful
Go to your "MyMap" map. Click on the three dots next to the name of the map, click on "Export to KML":
Choose the "Keep data up to date with network link KML (only usable online):
Rename the .kmz file to .zip, then open it and open the doc.kml file it contains. That file will have the direct link to the KML data specifying your "MyMap".
Use that link in a google.maps.KmlLayer
proof of concept fiddle
original MyMap
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {
lat: 41.876,
lng: -87.624
}
});
var ctaLayer = new google.maps.KmlLayer({
url: 'https://www.google.com/maps/d/kml?mid=1-mpfnFjp1e5JJ1YkSBjE6ZX_d9w',
map: map
});
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<div id="map"></div>
<!-- add your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">
</script>

Doing a Google Maps reverse geocode and displaying the result as part as HTML content inside an infowindow

I have put together this script (note: I'm using jQuery 1.11.2) that gets lat long coordinates from a PHP operation (used for something else) and displays a map with a customized marker and infowindow that includes HTML for formatting the information that is displayed.
<script src="https://maps.googleapis.com/maps/api/js?v=3.20&sensor=false"></script>
<script type="text/javascript">
var maplat = 41.36058;
var maplong = 2.19234;
function initialize() {
// Create a Google coordinate object for where to center the map
var latlng = new google.maps.LatLng( maplat, maplong ); // Coordinates
var mapOptions = {
center: latlng,
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
streetViewControl: false,
zoomControl: false,
mapTypeControl: false,
disableDoubleClickZoom: true
};
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
// CREATE AN INFOWINDOW FOR THE MARKER
var content = 'This will show up inside the infowindow and it is here where I would like to show the converted lat/long coordinates into the actual, human-readable City/State/Country'
; // HTML text to display in the InfoWindow
var infowindow = new google.maps.InfoWindow({
content: content,maxWidth: 250
});
var marker = new google.maps.Marker( {
position: latlng,
map: map,
title: "A SHORT BUT BORING TITLE",
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
infowindow.open(map,marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
What I'm trying to achieve is to do a reverse geocode on the coordinates stored in the latlng variable and get back the results of that in a "City, State, Country" format and insert that into the HTML for the informarker stored in the "content" variable.
Have tried multiple approaches without success. Please note that I've deliberately left out the reverse geocoding script I tried to use for clarity purposes.
Edit: I've adjusted the script presented here to comply with the rules about it being clear, readable and that it actually should work. I also include a link to a CodePen so that you can see it in action: Script on CodePen
Regarding including the script for reverse geocoding, what I did was a disaster, only breaking the page and producing "undefined value" errors. I'd like to learn the correct way of doing this by example, and that's where the wonderful StackOverflow community comes in. Thanks again for your interest in helping me out.
Use a node instead of a string as content , then you may place the geocoding-result inside the content, no matter if the infoWindow is already visible or not or when the result is available(it doesn't even matter if the InfoWindow has already been initialized, a node is always "live").
Simple Demo:
function initialize() {
var geocoder = new google.maps.Geocoder(),
latlng = new google.maps.LatLng(52.5498783, 13.42520);
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 18,
center: latlng
}),
marker = new google.maps.Marker({
map: map,
position: latlng
}),
content = document.createElement('div'),
infoWin = new google.maps.InfoWindow({
content: content
});
content.innerHTML = '<address>the address should appear here</address>';
google.maps.event.addListener(marker, 'click', function() {
infoWin.open(map, this);
});
geocoder.geocode({
location: latlng
}, function(r, s) {
if (s === google.maps.GeocoderStatus.OK) {
content.getElementsByTagName('address')[0].textContent = r[0].formatted_address;
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
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"></script>
<div id="map-canvas"></div>
Here's how I would do it:
function reverseGeocoder(lat, lng, callback) {
var geocoder = new google.maps.Geocoder();
var point = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
geocoder.geocode({"latLng" : point }, function(data, status) {
if (status == google.maps.GeocoderStatus.OK && data[0]) {
callback(null, data[0].formatted_address);
} else {
console.log("Error: " + status);
callback(status, null);
}
});
};
And basically you would call the function like:
reverseGeocoder(lat, lng, function(err, result){
// Do whatever has to be done with result!
// EDIT: For example you can pass the result to your initialize() function like so:
initialize(result); // And then inside your initialize function process the result!
});

Google Map not showing up on my page

i am trying to implement google map in chrome, however the geolocation doesn't seems to be working i also changed the setting to 'allow all site to track'
i have taken these code from a tutorial online, and hence i couldn't find a way to make it work
<head>
<title>Map</title>
<!-- Google Maps and Places API -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function initGeolocation(){
if( navigator.geolocation ){
// Call getCurrentPosition with success and failure callbacks
navigator.geolocation.getCurrentPosition( success, fail );
}else{
alert("Sorry, your browser does not support geolocation services.");
}
}
var map;
function success(position){
// Define the coordinates as a Google Maps LatLng Object
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Prepare the map options
var mapOptions = {
zoom: 14,
center: coords,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Create the map, and place it in the map_canvas div
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//search for schools within 1500 metres of our current location, and as a marker use school.png
//placesRequest('Schools',coords,1500,['school']);
// Place the initial marker
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "Your current location!"
});
}
function fail(){
// Could not obtain location
}
//Request places from Google
function placesRequest(title,latlng,radius,types,icon){
//Parameters for our places request
var request = {
location: latlng,
radius: radius,
types: types
};
//Make the service call to google
var callPlaces = new google.maps.places.PlacesService(map);
callPlaces.search(request, function(results,status){
//trace what Google gives us back
$.each(results, function(i,place){
var placeLoc = place.geometry.location;
var thisplace = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon,
title: place.name
});
})
});
}
</script>
initGeolocation() is not fired anywhere.
The div with id map_canvas is missing and you don't call initGeolocation function anywhere in your code .
Check here , everything works ok

Categories

Resources