0

I am working on a project in which I want to make a circle around the location of an item on a google map. In my below code if I click show tab then it should show circle around item's location on a google map:

<div class="tab-pane" id="show">
 <p>
    <span class="heading_size">show:</span>
 </p>

 <p class="text-justify mb-0 pb-5">
   <!-- <? php echo strtolower($data['item']->item_address); ?> -->
    <div id="map" style="width:100%;height:500px"></div> 

    <script>
    function myMap() {
      var amsterdam = new google.maps.LatLng(52.395715,4.888916);
      var mapCanvas = document.getElementById("map");
      var mapOptions = {center: amsterdam, zoom: 7};
      var map = new google.maps.Map(mapCanvas,mapOptions); 

      var myCity = new google.maps.Circle({
        center: amsterdam,
        radius: 50000,
        strokeColor: "#0000FF",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#0000FF",
        fillOpacity: 0.4
      });

      myCity.setMap(map);
    }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>
 </p>
</div>


Problem Statement:

Below is the item details that gets printed out when I print item_address as shown in the above code (commented at this moment) using echo. So I need to use below data to make a circle around city field in the below json. For example: in the below json - city field is ottawa so it should make circle around ottawa city. As of now I can make circle around a particular lat/long but instead if I have a city name, then how can I make a circle around that city? Is this possible to do?

{
    "address_id": 115,
    "country": "canada",
    "state": "ontario",
    "city": "ottawa",
    "street": "riverside drive",
    "number": "1750",
    "postal": "k1g 3t6"
}
flash
  • 1,455
  • 11
  • 61
  • 132

3 Answers3

1

You need to use Gecoding to find out position of city on the map. You can take a look at working example below.

I have created following function which allows you to draw circle around any city that you pass to the function:

google.maps.event.addDomListener(window, "load", function() {
  myMap();
});

function myMap() {
  //add global geocoder
  window.geocoder = new google.maps.Geocoder();

  var mapCanvas = document.getElementById("map_div");
  var mapOptions = {
    zoom: 7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: new google.maps.LatLng(33.808678, -117.918921)
  };
  window.map = new google.maps.Map(mapCanvas, mapOptions);

  drawCircleAroundCity('ottawa');
}

function drawCircleAroundCity(cityName) {
  if (!cityName) return;
  if (!window.geocoder) throw "Geocoder is not loaded";

  window.geocoder.geocode({
    'address': cityName
  }, function(results, status) {
    if (status == 'OK') {
      addCircle(results[0].geometry.location, true);
    } else {
      throw 'Unable to find address: ' + address;
    }
  });
}

function addCircle(position, recenter) {
  if (typeof(position) != 'object') return;
  if (!window.map) throw "Map is not loaded";

  var myCity = new google.maps.Circle({
    center: position,
    radius: 50000,
    strokeColor: "#0000FF",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#0000FF",
    fillOpacity: 0.4
  });

  myCity.setMap(window.map);

  if (recenter)
    window.map.setCenter(position);
}
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&amp;sensor=false"></script>
<div id="map_div" style="height: 400px;"></div>
Dipen Shah
  • 25,562
  • 1
  • 32
  • 58
  • Sorry I was out for a while. I copied your suggestion into a html file but when I run it, it doesn't load anything at all. Here is my full HTML [file](https://pastebin.com/raw/4vJFaBCA). Do you see anything wrong in my file? – flash Aug 25 '18 at 02:24
  • @flash cannot access your file, it's private. – Dipen Shah Aug 25 '18 at 03:10
  • Can you try now? I made it public – flash Aug 25 '18 at 03:12
  • @flash Move your script to the end of body. – Dipen Shah Aug 25 '18 at 03:29
  • yeah it works fine now. Sorry for stupid mistake. I have another [question](https://stackoverflow.com/questions/52014472/how-to-calculate-distance-of-an-item-from-current-location-and-show-it-in-a-text) which I created just now. In this I am trying to calculate distance of an item from current location and show it in a text. Wanted to see if you can help me out. – flash Aug 25 '18 at 06:01
  • you still around? – flash Aug 25 '18 at 16:46
  • I did see your question but there is no code for me to look at, it'll be best if you can post some code so anyone can take a look at the problem. – Dipen Shah Aug 25 '18 at 17:36
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178750/discussion-between-flash-and-dipen-shah). – flash Aug 25 '18 at 17:37
0

Use the Google Maps Geocoding API and construct the appropriate request from your JSON fields. The API will return a JSON object containing the the latitude and longitude values.

Your API request will be in the form of:

https://maps.googleapis.com/maps/api/geocode/json?address=1750+riverside+drive,ottawa,ontario,canada&key=YOUR_API_KEY
Dan Nagle
  • 4,384
  • 1
  • 16
  • 28
  • *Something like this:* `https://maps.googleapis.com/maps/api/geocode/json?address= $data['item']->item_address->number $data['item']->item_address->street $data['item']->item_address->city $data['item']->item_address->state $data['item']->item_address->country $data['item']->item_address->postal&key=YOUR_API_KEY` – flash Aug 19 '18 at 19:07
0

Translating a city to LatLon can't be too hard but here's some code I could copy blindly without thinking too much. HTH.

    var circleOptions = {
      clickable: true,
      draggable: true,
      editable: true,
      visible: false,
      strokeColor: 'gray',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: 'gray',
      fillOpacity: 0.35,
      center: marker.getPosition()
    };

    radarCircle = new radarView(new google.maps.Circle(circleOptions));

    google.maps.event.addDomListener(radarCircle,    'center_changed', reScope);
    google.maps.event.addDomListener(radarCircle,    'radius_changed', reScope);

function radarView(superBase)
{
    this.__proto__ = superBase;

    if (this instanceof google.maps.Circle) {
        augmentCircle.apply(this);
    } else if (this instanceof google.maps.Rectangle) {
        augmentRectangle.apply(this);
    } else {
        Tier3Toolbox.reportError({header:"Internal error", 
                message:"Inheriting from unknown object"});
    }

    this.doX = function(x){return "x is>" + x;};

    return this;
}

function augmentCircle()
{
    this.moveBorder = function()
    {
        google.maps.event.trigger(radarCircle,"center_changed");
    }
}

function augmentRectangle()
{
    this.moveBorder = function()
    {
        google.maps.event.trigger(radarRectangle,"bounds_changed");
    }
}


function reScope() {

    var searchReq = {'cmd':'search', 'scopeVintage':scopeVintage};
    if (radarShape.getCenter) {
        searchReq.checker = 0;
        var currCenter = radarCircle.getCenter();
        searchReq.centerLat = currCenter.lat();
        searchReq.centerLng = currCenter.lng();         
        searchReq.radius = radarCircle.getRadius();
    } else {
        searchReq.checker = 1;
        searchReq.SWLat = radarShape.getBounds().getSouthWest().lat();
        searchReq.SWLng = radarShape.getBounds().getSouthWest().lng();
        searchReq.NELat = radarShape.getBounds().getNorthEast().lat();
        searchReq.NELng = radarShape.getBounds().getNorthEast().lng();
    }

    facFinder.postMessage(searchReq);
}
McMurphy
  • 1,235
  • 1
  • 15
  • 39