Google Maps API3 with default Popup & Marker? - google-maps-api-3

Is it possible to show the default Google Maps icon and popup on a custom map?
The default one with the address, title directions nearby etc etc.
This is how i've currently got it set up and working fine apart from the marker..
var map;
jQuery(function($) {
function initialize() {
var styles = [
{
stylers: [
{ "saturation": -100 }
]
}
];
var styledMap = new google.maps.StyledMapType(styles,
{name: "Styled Map"});
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(55.6468, 37.581),
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
}
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
}
google.maps.event.addDomListener(window, 'load', initialize);
});

Is it possible to show the default Google Maps icon and popup on a custom map?
The default marker is easy, see the documentation, but the answer for the Google Maps default infowindow is no, but you can create your own infowindow that looks similar and has similar functionality.

Related

Inset Map in Google Maps API

I haven't been able to find this answer in the Maps API documentation, but is it possible to have an "inset" map using the Google Maps API?
It seems like it is doable with the Maps Embed API (see lower left corner), but you can't customize the map with this API.
I ended up making my own. I don't know why this question was downvoted. Anyway, check out my JSFiddle here: http://jsfiddle.net/wLuhktu4/1/
function initialize() {
var mapOptions = {
zoom: 17,
center: {
lat: -33.8666,
lng: 151.1958
},
disableDefaultUI: true
};
var overviewMapOptions = {
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE,
center: {
lat: -33.8666,
lng: 151.1958
},
disableDefaultUI: true
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var overviewMap = new google.maps.Map(document.getElementById('overview-map'), overviewMapOptions);
google.maps.event.addListener(map, 'bounds_changed', (function () {
overviewMap.setCenter(map.getCenter());
overviewMap.setZoom(map.getZoom());
}));
}
google.maps.event.addDomListener(window, 'load', initialize);
The problem (although minor) is that because this is not officially supported, the watermark and terms of use take up a lot of space on this inset map.
I hope this helps someone in the future.

Google map API geolocation after first display of the map

This code takes a big list of (400) markers and adds it to the map, at the end, it shows the whole map including all the markers.
What I have tried to achieve is: when geolocation is available, center the map on location, zoom to level 16 and refresh the map to show it, otherwise, let the whole big map show... I have read and tried many different things, but the geolocation must happen before the map is created. I want to make it happen after. I show you my code here and the temporary link to the working site: http://studioteknik.co/brasseursillimites.com/detaillants/
function initialize()
{
var map = new google.maps.Map(document.getElementById('map-canvas'));
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (var i in locations) {
var p = locations[i];
var latlng = new google.maps.LatLng(p[1], p[2]);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: p[0]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.title);
infowindow.open(map, this);
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
Here is a simple example of geolocation. Just add the geolocation code anywhere after the map object is created. If the user doesn't allow geolocation, the map will be shown at the default location / zoom level.
function initialize() {
var mapOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(0,0)
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// Geolocation code
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
map.setZoom(16);
});
}
}
initialize();
JSFiddle demo

Capture Coordinates in Google Map on User Click

I'm using this code to capture the co-ordinates when user clicks on the map by using below event listener:
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
However this function doesn't get called when user click on already marked location in Map.
Meaning this function is not called for points where mouse pointer changes to hand icon on Google Map.
Need help on capturing these kind of locations.
You should add the click listener on marker will give you the position of marker.
//Add listener
google.maps.event.addListener(marker, "click", function (event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
console.log( latitude + ', ' + longitude );
}); //end addListener
Edit:
You need something like this
//Add listener
google.maps.event.addListener(marker, "click", function (event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
console.log( latitude + ', ' + longitude );
radius = new google.maps.Circle({map: map,
radius: 100,
center: event.latLng,
fillColor: '#777',
fillOpacity: 0.1,
strokeColor: '#AA0000',
strokeOpacity: 0.8,
strokeWeight: 2,
draggable: true, // Dragable
editable: true // Resizable
});
// Center of map
map.panTo(new google.maps.LatLng(latitude,longitude));
}); //end addListener
Another solution is to place a polygon over the map, same size as the map rectangle, and collect this rectangles clicks.
function initialize() {
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var lat1 = 37.41463623043073;
var lat2 = 37.46915383933881;
var lng1 = -122.1848153442383;
var lng2 = -122.09898465576174;
var rectangle = new google.maps.Polygon({
paths : [
new google.maps.LatLng(lat1, lng1),
new google.maps.LatLng(lat2, lng1),
new google.maps.LatLng(lat2, lng2),
new google.maps.LatLng(lat1, lng2)
],
strokeOpacity: 0,
fillOpacity : 0,
map : map
});
google.maps.event.addListener(rectangle, 'click', function(args) {
console.log('latlng', args.latLng);
});
});
}
Now you get LatLng's for places of interest (and their likes) also.
demo -> http://jsfiddle.net/qmhku4dh/
You're talking about the Point of Interest icons that Google puts on the map.
Would it work for you to remove these icons entirely? You can do that with a Styled Map. To see what this would look like, open the Styled Map Wizard and navigate the map to the area you're interested in.
Click Point of interest under Feature type, and then click Labels under Element type. Finally, click Visibility under Stylers and click the Off radio button under that.
This should remove all of the point of interest icons without affecting the rest of the map styling. With those gone, clicks there will respond to your normal map click event listener.
The Map Style box on the right should show:
Feature type: poi
Element type: labels
Visibility: off
If the result looks like what you want, then click Show JSON at the bottom of the Map Style box. The resulting JSON should like this this:
[
{
"featureType": "poi",
"elementType": "labels",
"stylers": [
{ "visibility": "off" }
]
}
]
You can use that JSON (really a JavaScript object literal) using code similar to the examples in the Styled Maps developer's guide. Also see the MapTypeStyle reference for a complete list of map styles.
This example demonstrates the use of click event listeners on POIs (points of interest). It listens for the click event on a POI icon and then uses the placeId from the event data with a directionsService.route request to calculate and display a route to the clicked place. It also uses the placeId to get more details of the place.
Read the google documentation.
<!DOCTYPE html>
<html>
<head>
<title>POI Click Events</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="infowindow-content">
<img id="place-icon" src="" height="16" width="16">
<span id="place-name" class="title"></span><br>
Place ID <span id="place-id"></span><br>
<span id="place-address"></span>
</div>
<script>
function initMap() {
var origin = {lat: -33.871, lng: 151.197};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: origin
});
var clickHandler = new ClickEventHandler(map, origin);
}
/**
* #constructor
*/
var ClickEventHandler = function(map, origin) {
this.origin = origin;
this.map = map;
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
this.placesService = new google.maps.places.PlacesService(map);
this.infowindow = new google.maps.InfoWindow;
this.infowindowContent = document.getElementById('infowindow-content');
this.infowindow.setContent(this.infowindowContent);
// Listen for clicks on the map.
this.map.addListener('click', this.handleClick.bind(this));
};
ClickEventHandler.prototype.handleClick = function(event) {
console.log('You clicked on: ' + event.latLng);
// If the event has a placeId, use it.
if (event.placeId) {
console.log('You clicked on place:' + event.placeId);
// Calling e.stop() on the event prevents the default info window from
// showing.
// If you call stop here when there is no placeId you will prevent some
// other map click event handlers from receiving the event.
event.stop();
this.calculateAndDisplayRoute(event.placeId);
this.getPlaceInformation(event.placeId);
}
};
ClickEventHandler.prototype.calculateAndDisplayRoute = function(placeId) {
var me = this;
this.directionsService.route({
origin: this.origin,
destination: {placeId: placeId},
travelMode: 'WALKING'
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
ClickEventHandler.prototype.getPlaceInformation = function(placeId) {
var me = this;
this.placesService.getDetails({placeId: placeId}, function(place, status) {
if (status === 'OK') {
me.infowindow.close();
me.infowindow.setPosition(place.geometry.location);
me.infowindowContent.children['place-icon'].src = place.icon;
me.infowindowContent.children['place-name'].textContent = place.name;
me.infowindowContent.children['place-id'].textContent = place.place_id;
me.infowindowContent.children['place-address'].textContent =
place.formatted_address;
me.infowindow.open(me.map);
}
});
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"
async defer></script>
</body>
</html>
If you are using npm load-google-maps-api with webpack this worked for me:
const loadGoogleMapApi = require("load-google-maps-api");
loadGoogleMapApi({ key: process.env.GOOGLE_MAP_API_KEY }).then(map => {
let mapCreated = new map.Map(mapElem, {
center: { lat: lat, lng: long },
zoom: 7
});
mapCreated.addListener('click', function(e) {
console.log(e.latLng.lat()); // this gives you access to the latitude value of the click
console.log(e.latLng.lng()); // gives you access to the latitude value of the click
var marker = new map.Marker({
position: e.latLng,
map: mapCreated
});
mapCreated.panTo(e.latLng); // finally this adds red marker to the map on click.
});
});
Next if you are integrating openweatherMap in your app you can use the value of e.latLng.lat() and e.latLng.lng() which I console logged above in your api request. This way:
http://api.openweathermap.org/data/2.5/weather?lat=${e.latLng.lat()}&lon=${e.latLng.lng()}&APPID=${YOUR_API_KEY}
I hope this helps someone as it helped me.
Cheers!

Count and output number of markers bound by circle radius

I have a map thats populated with markers of places from a fusion table. I'm taking the users location and displaying a circle of radius 10 miles from their location. Here is my code - http://connormccarra.com/sandbox/map/. How can I use the api to count the number of markers bound by the circle and output that number in the footer?
Cheers!
Relevant code:
var map;
function Initialize() {
var MapOptions = {
zoom: 7,
center: new google.maps.LatLng(53.4125694, -8.245014),
mapTypeId: google.maps.MapTypeId.ROADMAP,
sensor: true
};
map = new google.maps.Map(document.getElementById("map_canvas"), MapOptions);
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'Address',
from: '1OPU6utSjRYwJSFK-EXdaGmt2KgLTq2loVIjS3AA'
}
});
layer.setMap(map);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
map: map,
position: pos,
content: 'You are here!'
});
// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
map: map,
radius: 16093, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');
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 count = mgr.getMarkerCount(circle);
document.getElementById("Address").innerHTML += count + "<BR>";
google.maps.event.addDomListener(window, 'load', initialize);
//Maps API loaded, now load customizations
var element = document.createElement('script');
element.src = 'template.js';
element.type = 'text/javascript';
var scripts = document.getElementsByTagName('script')[0];
scripts.parentNode.insertBefore(element, scripts);
}
The markers created by a FusionTableLayer are not real markers, there is no way to get them as a kind of list to filter them(you can't get any details for the markers, except you click them).
But you may request the FusionTableAPI with a spatial condition(via AJAX, jsonp is supported).
The syntax for the query:
SELECT COUNT() from tableId
WHERE ST_INTERSECTS('Address',CIRCLE(LATLNG(lat,lng),10000))
How to send a query : https://developers.google.com/fusiontables/docs/v1/sql-reference
Demo(using data of another FusionTable because your table is protected):
http://jsfiddle.net/doktormolle/bAtgf/
Simplest way: use the geometry library computeDistanceBetween method. If the distance from the user's location is less than 10 miles, the marker is in the circle.
I suggest you first fetch all the coordinates of your FusionTablesLayer.
Here is an example which was used in the sidebar
http://www.geocodezip.com/v3_FusionTables_AfricaMap_kml_sidebar.html
Then using a loop statement you can use the computeDistanceBetween function.
Detect If Marker is Within Circle Overlay

How can I use Google Maps API to import KML and click on polygons?

Basically I have a KML file that has a TON of polygons to be mapped out. I need those polygons to be clickable in which I'd perform an ajax response.
I'm pretty lost, though. Can someone point me in the right direction? :)
Check out the polygon-array example that the Google Maps documentation refers to. It shows how to draw polygons, and how to respond to clicks on such polygons.
To view the example:
http://code.google.com/apis/maps/documentation/javascript/examples/polygon-arrays.html
To view the source-code behind it:
view-source:http://code.google.com/apis/maps/documentation/javascript/examples/polygon-arrays.html
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(41.376259, 25.055542),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var Place = new google.maps.KmlLayer({
url: 'path-to-kml.kml'
});
Place.setMap(map);
google.maps.event.addListener(Place, 'click', function (event) {
window.location.href = 'http://example.com'
});
}
google.maps.event.addDomListener(window, 'load', initialize);

Resources