Google maps v3 geocode multiple custom markers by address or latlng - google-maps-api-3

I need to plot multiple custom map markers using MapsV3 api either by an address or lat/lon. I put together the following code which works ok for lon/lat, but if the data contains an address the geocoder returns nothing. Any ideas on how to fix this.
$(document).ready(function () { initialize(); });
function initialize() {
var centerMap = new google.maps.LatLng(-27.0,133.0);
var options = {
panControl: false,
zoomControl: true,
scaleControl: false,
mapTypeControl: false,
streetViewControl: false,
zoom: 3,
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), options);
var data = [
{
'title':'F C Building Construction ...',
'address':'',
'zindex':20,
'lat':'-33.797847',
'lon':'151.259928',
'marker_number':1,
'marker_html':' html content...',
'image': {
url:'//localhost/assets/images/markers/marker_1.png',
size: new google.maps.Size(24, 29),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(10, 29)
}
}];
setMarkers(map, data);
var infowindow = new google.maps.InfoWindow();
}
function showMapPin(i) { }
function setMarkers(map,data) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < data.length; i++) {
setMarker(map, data[i], bounds);
}
map.fitBounds(bounds);
}
function setMarker(map, m, bounds) {
if(m["address"]!="") {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { "address": m["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var siteLatLng = results[0].geometry.location;
}
});
} else {
var siteLatLng = new google.maps.LatLng(m["lat"], m["lon"]);
}
if(siteLatLng) {
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
//shadow: shadow,
icon: m["image"],
title: m["title"],
zIndex: m["zindex"],
html: m["marker_html"]
});
bounds.extend(siteLatLng);
google.maps.event.addListener(marker, "click", function() {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
} // if latlng
}//]]>

After looking back over the code I realized that the variable siteLatLng is within geocode function scope so it never gets passed and it can't be returned. Setting the marker within this function works.

Related

Remove Bounds icon on google maps marker

currently I created pages with google maps api v3, and there is a marker that user can drag. after dragend, the script with draw blue line on the road between marker. my problem is shown 2 marker on destination (a marker and "B" marker)
I've try using fitbounds() but still facing my problem.
<div id="current"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=xxx"></script>
<script type="text/javascript">
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(-7.760722, 110.408761),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-7.760722, 110.408761),
map: map,
draggable:true
});
google.maps.event.addListener(
marker,
'dragend',
function() {
console.log(marker.position.lat());
console.log(marker.position.lng());
var msv = new google.maps.LatLng(-7.760722, 110.408761);
var mgw = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
var request = {
origin: msv,
destination: mgw,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections(response);
directionsDisplay.setMap(map);
}
else
{
alert("Directions Request from " + start.toUrlValue(6) + " to " + end.toUrlValue(6) + " failed: " + status);
}
});
}
);
how to remove bound marker ("B" marker) on destination? I expect there is only one marker in destination
You need to remove all the markers (with the {suppressMarkers:true} option on the DirectionsRenderer (they can't be suppressed separately)
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
To make the "A" Marker appear, create it:
var markerA = new google.maps.Marker({
map: map,
position: msv,
label: {
text: "A",
color: "white"
}
})
proof of concept fiddle
code snippet:
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(-7.760722, 110.408761),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-7.760722, 110.408761),
map: map,
draggable: true
});
google.maps.event.addListener(
marker,
'dragend',
function() {
console.log(marker.position.lat());
console.log(marker.position.lng());
var msv = new google.maps.LatLng(-7.760722, 110.408761);
var mgw = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
// add "A" marker
var markerA = new google.maps.Marker({
map: map,
position: msv,
label: {
text: "A",
color: "white"
}
})
var request = {
origin: msv,
destination: mgw,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
directionsDisplay.setMap(map);
} else {
alert("Directions Request from " + start.toUrlValue(6) + " to " + end.toUrlValue(6) + " failed: " + status);
}
});
}
);
html,
body,
#map_canvas {
height: 100%;
margin: 0;
padding: 0;
}
<div id="current"></div>
<div id="map_canvas"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

Implementing google place autocomplete

This is my code for places autocomplete and search.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
This is my html code.
<input id="address" type="textbox" size="30">
<input type="button" value="Search" onclick="codeAddress()">
It is working fine but I dont want to user to click the button. When suggestions appeared, and when user select any of suggestion options, map will have to navigate to that place. How do I do this???
When User select any option from dropdown, map should navigate to that place.
Take a look at this example and the implementation of the place_changed event.
var place = autocomplete.getPlace();
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
}
This way you can pan the map to the location of the autocomplete result.
This is my working code..
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Now user can select option from dropdown and map will navigate to that place. And also on search button click.
Hope this might help you
function initialize(){
var mapOptions = {//Map Properties
zoom:12,
center: Bangalore
};
googleMap = new google.maps.Map(document.getElementById('map-holder'),mapOptions);//map-holder is a div which holds map in my html
var defaultBounds = new google.maps.LatLngBounds(//bounds for Bengaluru
new google.maps.LatLng(12.7342888,77.3791981),
new google.maps.LatLng(13.173706,77.8826809)
);
googleMap.fitBounds(defaultBounds);
var input = (document.getElementById('searchInput'));//search input element
googleMap.controls[google.maps.ControlPosition.TOP_LEFT].push(input);//binding it to map
var searchBox = new google.maps.places.SearchBox((input));
google.maps.event.addListener(searchBox, 'places_changed', function() {//triggers when search is performed
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
bounds.extend(place.geometry.location);
//googleMap.fitBounds(place.geometry.viewport);
}
googleMap.fitBounds(bounds);
});
google.maps.event.addListener(googleMap, 'bounds_changed', function() {
var bounds = googleMap.getBounds();
searchBox.setBounds(bounds);
})
}

Google maps. Blank Image

I tried everything I could think of, but the first time the page loads I have a blank google gray image, after refresh is working.
<script>
var latitude,longitude;
function GetLocationInstant() {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': '7521 Reindeer Ct, Las Vegas, NV 89147' /* This address will come from a post variable*/ }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
// console.log("Latitude: " + latitude + "\nLongitude: " + longitude);
} else {
console.log("geocoder.geocode() failed.<?php echo $address; ?>");
}
});
};
var map;
function initializeInstant() {
var image = "http://example.com/wp-content/themes/mytheme/icon.gif";
// console.log(latitude,longitude);
var myLatlng = new google.maps.LatLng(latitude,longitude);
var mapOptions = {
zoom: 20,
center: myLatlng,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image
});
}
GetLocationInstant();
if ('undefined'!==latitude&&'undefined'!==longitude)
google.maps.event.addDomListener(window, "load", initializeInstant);
</script>
<div style="height: 200px;margin-bottom: 20px;padding: 0px" id="map-canvas"></div>
How can I get the a google map Image searching by address?
EDIT: http://jsfiddle.net/qzygw4jL/4/
Geocoding is an asynchronous operation and you're not waiting for the result before initializing the map. You should call initializeInstant() inside the geocoder callback like this:
var latitude,longitude, map;
function GetLocationInstant() {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address' : '7521 Reindeer Ct, Las Vegas, NV 89147 '
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
// Initialize map after address is found
initializeInstant();
} else {
console.log("geocoder.geocode() failed.<?php echo $address; ?>");
}
});
};
function initializeInstant() {
var image = "http://example.com/wp-content/themes/mytheme/icon.gif";
var myLatlng = new google.maps.LatLng(latitude,longitude);
var mapOptions = {
zoom: 20,
center: myLatlng,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image
});
}
google.maps.event.addDomListener(window, "load", GetLocationInstant);
Working demo

I could not delete polygon when marker is click

I am trying to delete a polygon when my marker is being clicked,but i could not get how to make this work that the polygon will be deleted.I appreciate someone will help me to make this work.
This my demo in jsfiddle.
Demo
here is my code it's not working.
var map;
var count = 0;
var polycolor = '#ED1B24';
var polyarray = [];
var marker;
var markers = [];
var path = new google.maps.MVCArray;
function initialize() {
var initial = new google.maps.LatLng(53.199246241276875, -105.76864242553711);
var mapOptions = {
zoom: 16,
center: initial,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeControl: false
};
poly.setPaths(new google.maps.MVCArray([path]));
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
addMarker(e);
addPolygon(e);
});
}
var deletepolygon = function (pt) {
i = 0;
var thepath = poly.getPath();
thepath.forEach(function (ltlng) {
i++;
if ((ltlng.lat() + "," + ltlng.lng()) == pt) {
path.removeAt(i);
}
});
}

Google Map Marker not being replaced

please excuse a noob at this. When a user clicks on a map, it should place a marker and open an info window - as per this example: http://www.geocodezip.com/v3_example_click2add_infowindow.html
The code below almost works correctly, except that the mark is not replaced - a new one is added. Any ideas really, really gratefully received. Thank you.
<script>
var map = null;
var markersArray = [];
function initialize() {
var latlng = new google.maps.LatLng(0.0000, 0.0000);
var settings = {
zoom: 2,
mapTypeControl:true,
center: latlng,
panControl:true,
zoomControl:true,
streetViewControl:false,
overviewMapControl:false,
rotateControl:true,
scaleControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'white'
};
map = new google.maps.Map(document.getElementById('map'), settings);
function placeMarker(location) {
var marker , i ;
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
icon:'http://www.desperatesailors.com/templates/Live/media/mapicons/info.png',
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() +
'<br>Longitude: ' + location.lng() +
'<br>Only the first four decimal places needed'
});
infowindow.open(map,marker);
}
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
window.onload = initialize;
</script>
This is a scope issue. You are always delcaring marker in the placeMarker function so if( marker ) will always be false. Move the variable declaration out of that function:
<script>
var marker;
var map = null;
var markersArray = [];
function initialize() {
var latlng = new google.maps.LatLng(0.0000, 0.0000);
var settings = {
zoom: 2,
mapTypeControl:true,
center: latlng,
panControl:true,
zoomControl:true,
streetViewControl:false,
overviewMapControl:false,
rotateControl:true,
scaleControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'white'
};
map = new google.maps.Map(document.getElementById('map'), settings);
function placeMarker(location) {
var i ;
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
icon:'http://www.desperatesailors.com/templates/Live/media/mapicons/info.png',
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() +
'<br>Longitude: ' + location.lng() +
'<br>Only the first four decimal places needed'
});
infowindow.open(map,marker);
}
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
window.onload = initialize;
</script>
Your placeMarker function creates a new (empty) marker variable in the local scope.
function placeMarker(location) {
var marker , i ;
if ( marker ) {
It will always create a new marker. Change it to:
var marker = null;
function placeMarker(location) {
if ( marker ) {

Resources