I'm using the latest Google map API v3 and trying to accomplish the following:
Center users on the map when the page loads on a mobile device. I have this working in the code below.
The ability for users to click/touch a POI from the map and view the info window. This is also working since its a basic feature of google maps.
This is were I'm stumped. I need to be able to populate 2 fields with the name of the POI from the Info-Window in the 1st field and the 2nd field the Place-ID.
Here's what I've found so far:
https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder
This link allows searching of places and the marker that is populated produces a Info-Window with the Place-ID of the searched location. But if you click on any of the POIs outside the marker, there are no Place_IDs.
The other close solution:
Get placeId on google maps when POI is clicked
This solution allows you to click and see the Place-ID but there are 2 main issues. 1st, the same POI from the first link above produces a different Place-ID than this solution for the exact same location. Additionally it produces a Place-ID for any point on the map regardless if a POI is near.
Here's my code thus far:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 17,
streetViewControl: false,
mapTypeControl: false
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
I would greatly appreciate any light that could be shed on why the Place-IDs are always different between these methods and possible solutions on getting the true Place-ID from a click event. Thank you!
You can listen the click events on the map. If you click on the POI icon the IconMouseEvent will be raised.
According to the documentation:
google.maps.IconMouseEvent object specification
This object is sent in an event when a user clicks on an icon on the map. The place ID of this place is stored in the placeId member. To prevent the default info window from showing up, call the stop() method on this event to prevent it being propagated. Learn more about place IDs in the Places API developer guide.
This object extends MouseEvent.
Please have a look at this sample code to figure out how to use events with Place ID:
http://jsbin.com/parapex/10/edit?html,output
Hope it helps!
Related
I'm building a tracking application that use Google Maps and as a result has multiple markers the user can click on. The page will eventually refresh every 15 minutes or so to keep up with the latest tracking data. However I want to give the the user to stick with the selected marker even after a page refresh so if needs be they can follow the selected vehicle (which the marker represents).
I've tried to achieve this using the local storage. I can get the lat and long into the storage no problem but when I come to get it out I've found that the longitude has come out with too many decimal places so the API won't recognise the position.
To go to the marker after the refresh my code is like this:
var centre = {lat: 53.806590, lng: -1.548437};
var centreRefresh = localStorage.getItem("markerPos");
// Draw the map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: centre
});
if (centreRefresh != null && $("#zoomRefresh").is(':checked')) {
map.setZoom(8);
map.setCenter(centreRefresh);
}
And to fill the local storage I have this:
// Add Info Window to Marker
marker.addListener('click', function() {
infowindow.open(map, marker);
if ($("#zoomRefresh").is(':checked')) {
markerPos = marker.getPosition();
localStorage.setItem("markerPos", markerPos);
}
map.setZoom(8);
map.setCenter(marker.getPosition());
});
The optput in the console from that is set in the local storage is "(55.823772, -2.8525829999999814)" and the error message is InvalidValueError: setCenter: not a LatLng or LatLngLiteral: not an Object Is there a better way to do this as this method doesn't seem to be working correctly?
first of all I was initiate marker from geojson, and how I can get the marker if i want use marker for listener/action?
this is my script
var map;
function initMap() {
//makes map
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -6.9034482, lng: 107.6081381},
zoom: 9,
styles: [{"featureType":"water","stylers":[{"saturation":43},{"lightness":-11},{"hue":"#0088ff"}]},{"featureType":"road","elementType":"geometry.fill","stylers":[{"hue":"#ff0000"},{"saturation":-100},{"lightness":99}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"color":"#808080"},{"lightness":54}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#ece2d9"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"color":"#ccdca1"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#767676"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]},{"featureType":"poi","stylers":[{"visibility":"off"}]},{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#b8cb93"}]},{"featureType":"poi.park","stylers":[{"visibility":"on"}]},{"featureType":"poi.sports_complex","stylers":[{"visibility":"on"}]},{"featureType":"poi.medical","stylers":[{"visibility":"on"}]},{"featureType":"poi.business","stylers":[{"visibility":"simplified"}]}]
});
//load marker from geojson
map.data.loadGeoJson('<?php echo base_url().'index.php/json_site/geojsongetmap'?>');
// set style marker
map.data.setStyle(function(feature){
var tit = feature.getProperty('nm_site');
return{
title: tit,
icon: '<?php echo base_url()?>assets/images/mark3.png'
};
});
//marker event
map.data.addListener(marker, 'click', function(event) {
map.setZoom(11);
map.setCenter(marker.getPosition()); // I need to get the position of the marker who i clicked
});
}
how I can make action listener if I initiate marker from geojson?
and how I can get the marker who existing in my map?
please help me, any suggest would be appreciated
thanks
Instances of the google.maps.Data.Point class are not exactly a drop-in replacement for traditional google.maps.Marker objects. For starters, they are abstract data, not tied to a particular representation. It's up to the parent google.maps.Data layer to decide how to draw them.
However, you can still capture events, with the caveat that the click happens on the Data layer, which receives a mouseEvent as argument. This argument contains the feature over which you just clicked.
This means you need to declare:
google.maps.event.addListener(map.data,'click',function(mouseEvent) {
var clickedFeature = mouseEvent.feature,
featureGeometry = clickedFeature.getGeometry(),
featurePosition = featureGeometry.get();
map.setCenter(featurePosition);
});
Please take into consideration that ingesting geoJson with the Data layer can result not just in Point geometries. If you get a mix of points, polygons and linestrings, anything different from a point won't return a latLng object when you call its get method.
I used to use an iFrame to embed a Google Map in a web page, but have recently switched to the JavaScript API to give myself more flexibility.
I am loading the map using the co-ordinates, which is working relatively well.
However, when I view a business on Google maps or in an iFrame for that matter, I can see the business I'm trying to focus on, highlighted in red:
But I can't seem to achieve this with the API -- which sometimes doesn't show the business name at all, let alone highlight it red. I've used DHL as an example here.
How can I 'bind' the map to a business location using the JS API?
My current script looks much like the one provided by the Google walkthrough pages:
function initialize() {
var longLat = { lat: 52.8004265, lng: -1.6334708},
mapOptions = {
center: longLat,
zoom: 18,
scrollwheel: false,
};
var map = new google.maps.Map(
document.getElementById('map-canvas'),
mapOptions
);
var marker = new google.maps.Marker({
position: longLat,
map: map,
title:"DHL"
});
}
google.maps.event.addDomListener(window, 'load', initialize);
You can attach infowindow to your marker and display the business name in that way. Here is an example
And here's another example using customized label as a marker, and it can contain the business name. Example
I'm having a rather strange issue with the Google Maps javascript API and HTML5 geolocation.
I have the following executed onload:
var geocoder;
var map;
var latlng;
function initialize() {
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
});
}else{
latlng = new google.maps.LatLng(geoip_latitude(),geoip_longitude());
}
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 8,
center: latlng,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
var latLong = String(event.latLng).replace('(', '');
latLong = latLong.replace(')', '');
$('#latlng').attr('value', latLong);
});
function placeMarker(location) {
if(undefined != initialize.marker){
initialize.marker.setMap(null);
}
initialize.marker = new google.maps.Marker({
position: location,
map: map
});
initialize.marker.setMap(map);
map.setCenter(location);
}
}
Now, what this should do is if the browser supports geolocation, get the lat+long, create a map, and display the map centered on the lat+long.
It works just fine if I use the geoip_ functions (maxmind), but the geolocation has a strange issue:
If the code is run as is, the google maps display shows up as a gray box with no map and no controls.
If I add an alert(); immediately after
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
});
}else{
latlng = new google.maps.LatLng(geoip_latitude(),geoip_longitude());
}
the map displays just fine.
What's up with that?
The W3C Geolocation API is asynchronous; the success callback function you have (which sets the variable latlng) won't be called immediately -- the browser requires some time to actually do the geolocating; in fact, if the user takes some time to read the privacy prompt and decide whether or not to give permission, this process could take many seconds. In the meantime though, your map is loaded immediately.
You're probably finding that it works with an alert after it because the alert gives the browser some time to finish the geolocation process and call the callback before getting to the code that loads the map. (Just waiting a second or two isn't a good solution though: some users and browsers will take much longer than that before revealing location.)
To fix: call the function that creates the map (you'll want to encapsulate practically everything after the geolocation call) and call it both in the success callback for getCurrentPosition and in the geoip else branch. That way you'll only try to load the map after you're guaranteed that the latlng variable has been appropriately filled.
I worked through this mess for the first time this morning (honestly I am surprised the maps API doesn't have a function to deal with this). Here is My Solution: JSFIddle
I want to clear a marker on Google Maps.
What is the difference between marker.setVisible(false) and marker.setMap(null)?
But I don't know, which is right?
The difference between the two methods does not seem to be clearly documented. However, note the following:
When you use setMap(null), your marker will lose the reference to the Map. If you do not keep a reference to the Map object, you wouldn't be able to reshow the marker.
In addition, the setMap() method will not trigger the visible_changed event, while the setVisible() method does (if the visibility is actually toggled).
Example:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(-25.363, 131.044),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-25.363, 131.044),
map: map
});
google.maps.event.addListener(marker, 'visible_changed', function() {
console.log('visible_changed triggered');
});
marker.setVisible(false); // visible_changed triggered
marker.setVisible(true); // visible_changed triggered
marker.setMap(null); // visible_changed not triggered
marker.setMap(map); // visible_changed not triggered
I guess we should be using the setVisible(false) method when we intend to reshow the marker again on the map, and the setMap(null) when we will not be showing it again.
Another key distinction is that setMap(NULL) releases the resources associated with the marker whereas setVisible(false) just makes the marker invisible, but the resources associated with the marker are still allocated.
If you're dealing with 100s or 1000s of markers, this can become a significant performance and memory issue.